You are given a 0-indexed integer array nums of length n.
The average difference of the index i is the absolutedifference between the average of the firsti + 1 elements of nums and the average of the lastn - i - 1 elements. Both averages should be
rounded down to the nearest integer.
Return the index with theminimum 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.
Input: nums =[2,5,3,9,5,3]Output: 3Explanation:
- The average difference of index 0is:|2/1-(5+3+9+5+3)/5|=|2/1-25/5|=|2-5|=3.- The average difference of index 1is:|(2+5)/2-(3+9+5+3)/4|=|7/2-20/4|=|3-5|=2.- The average difference of index 2is:|(2+5+3)/3-(9+5+3)/3|=|10/3-17/3|=|3-5|=2.- The average difference of index 3is:|(2+5+3+9)/4-(5+3)/2|=|19/4-8/2|=|4-4|=0.- The average difference of index 4is:|(2+5+3+9+5)/5-3/1|=|24/5-3/1|=|4-3|=1.- The average difference of index 5is:|(2+5+3+9+5+3)/6-0|=|27/6-0|=|4-0|=4.The average difference of index 3is the minimum average difference so return3.
To efficiently compute the average difference for each index, we use prefix sums to get the sum of the first i+1 elements and the sum of the last n-i-1 elements. This allows us to calculate averages in O(1) time for each index.
defminimum_average_difference(nums: list[int]) -> int:
n = len(nums)
prefix = [0]
for x in nums:
prefix.append(prefix[-1] + x)
total = prefix[-1]
min_diff = float('inf')
ans =-1for i in range(n):
left_avg = prefix[i+1] // (i+1)
right_avg = (total - prefix[i+1]) // (n-i-1) if n-i-1>0else0 diff = abs(left_avg - right_avg)
if diff < min_diff:
min_diff = diff
ans = i
return ans
classSolution {
funminimumAverageDifference(nums: IntArray): Int {
val n = nums.size
val prefix = LongArray(n+1)
for (i in nums.indices) prefix[i+1] = prefix[i] + nums[i]
val total = prefix[n]
var ans = -1var minDiff = Int.MAX_VALUE
for (i in0 until n) {
val leftAvg = (prefix[i+1] / (i+1)).toInt()
val rightAvg = if (n-i-1 > 0) ((total - prefix[i+1]) / (n-i-1)).toInt() else0val diff = kotlin.math.abs(leftAvg - rightAvg)
if (diff < minDiff) {
minDiff = diff
ans = i
}
}
return ans
}
}