[LeetCode] Minimum Average Difference

2256. Minimum Average Difference

You are given a 0-indexed integer array nums of length n.

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

Note:

  • The absolute difference of two numbers is the absolute value of their difference.
  • The average of n elements is the sum of the n elements divided (integer division) by n.
  • The average of 0 elements is considered to be 0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define all(a) begin(a), end(a)

using namespace std;

class Solution {
public:
int minimumAverageDifference(vector<int>& A) {
if(A.size() == 1) return 0;
long lsum = 0, rsum = accumulate(all(A),0l), n = A.size(), mi = LONG_MAX, res = -1;
for(int l = 0, r = n - 1; l < n - 1; l++,r--) {
lsum += A[l];
rsum -= A[l];

long lavg = lsum / (l + 1);
long ravg = rsum / (n - l - 1);
long diff = abs(lavg - ravg);
if(diff < mi) {
mi = diff;
res = l;
}
}
lsum = accumulate(all(A),0l) / n;
if(lsum < mi) return n - 1;
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/01/PS/LeetCode/minimum-average-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.