Skip to content

2256. Minimum Average Difference 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int minimumAverageDifference(vector<int>& nums) {
    const int n = nums.size();
    int ans = 0;
    int minDiff = INT_MAX;
    long prefix = 0;
    long suffix = accumulate(begin(nums), end(nums), 0L);

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i];
      suffix -= nums[i];
      const int prefixAvg = prefix / (i + 1);
      const int suffixAvg = (i == n - 1) ? 0 : suffix / (n - i - 1);
      const int diff = abs(prefixAvg - suffixAvg);
      if (diff < minDiff) {
        ans = i;
        minDiff = diff;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int minimumAverageDifference(int[] nums) {
    final int n = nums.length;
    int ans = 0;
    int minDiff = Integer.MAX_VALUE;
    long prefix = 0;
    long suffix = Arrays.stream(nums).asLongStream().sum();

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i];
      suffix -= nums[i];
      final int prefixAvg = (int) (prefix / (i + 1));
      final int suffixAvg = (i == n - 1) ? 0 : (int) (suffix / (n - i - 1));
      final int diff = Math.abs(prefixAvg - suffixAvg);
      if (diff < minDiff) {
        ans = i;
        minDiff = diff;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def minimumAverageDifference(self, nums: List[int]) -> int:
    n = len(nums)
    ans = 0
    minDiff = inf
    prefix = 0
    suffix = sum(nums)

    for i, num in enumerate(nums):
      prefix += num
      suffix -= num
      prefixAvg = prefix // (i + 1)
      suffixAvg = 0 if i == n - 1 else suffix // (n - i - 1)
      diff = abs(prefixAvg - suffixAvg)
      if diff < minDiff:
        ans = i
        minDiff = diff

    return ans