Minimum Average Difference Problem
Description
LeetCode Problem 2256.
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
nelements is the sum of thenelements divided (integer division) byn. - The average of
0elements is considered to be0.
Example 1:
Input: nums = [2,5,3,9,5,3]
Output: 3
Explanation:
- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.
- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.
- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.
- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.
- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.
- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.
The average difference of index 3 is the minimum average difference so return 3.
Example 2:
Input: nums = [0]
Output: 0
Explanation:
The only index is 0 so return 0.
The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^5
Solution
Approach: Prefix Sums in One Pass
Compute the total sum first. Then walk through the array while keeping pre, the sum of the first i + 1 elements, and suf, the sum of the rest. The two averages are pre / (i + 1) and suf / (n - i - 1) with integer division (the second is 0 when the suffix is empty). Compare the absolute difference with the best so far, and replace the answer only when it is strictly smaller, so the smallest index wins ties.
Complexity: O(n) time and O(1) space.
from math import inf
class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
pre, suf = 0, sum(nums)
n = len(nums)
ans, mi = 0, inf
for i, x in enumerate(nums):
pre += x
suf -= x
a = pre // (i + 1)
b = 0 if n - i - 1 == 0 else suf // (n - i - 1)
if (t := abs(a - b)) < mi:
ans = i
mi = t
return ans