2256. Minimum Average Difference
T: O(n)
S: O(1)
```java
class Solution {
public int minimumAverageDifference(int[] nums) {
long total = 0;
for (int num : nums) {
total += num;
}
int n = nums.length;
long result = Integer.MAX_VALUE;
int resultIdx = -1;
long prefixSum = 0;
long preCount = 0;
for (int i = 0 ; i < n; i++) {
prefixSum += nums[i];
preCount++;
long preAvg = (prefixSum/preCount);
long postAvg = n - preCount == 0 ? 0 : (total - prefixSum)/(n - preCount);
long avgDiff = Math.abs(preAvg - postAvg);
if (result > avgDiff) {
result = avgDiff;
resultIdx = i;
}
}
return resultIdx;
}
}
/**
i
i+1 n-i-1
abs(diff)
avg(first i+1 elements)
avg(last n - i - 1)
i = 1
0 1 2
first i+1 -> first 2
0 1 2
[ ]
last (3 - 1 - 1 = 1) -> last 1
0 1 2
[]
rounded down means
2.9 -> 2
2.4 -> 2
2.5 -> 2
find the index for min avg diff
ps = prefix sum of i
last_ps = sum - ps
ps / (0 to i) = ps / i+1
last_ps / n - i - 1
Min(Math.abs(ps - last_ps))
*/
```
Last updated