Sponsored
Sponsored
The idea is to use prefix sums to efficiently calculate the sum of elements up to any index and from any index to the end.
First, compute the prefix sum of the array. Use this prefix sum to calculate the sum of the first i+1 elements and the sum of the last n-i-1 elements. The prefixed sums allow these sums to be computed in constant time. For the entire array, calculate the absolute difference in averages at each index, keep track of the minimum difference, and return its index.
Time Complexity: O(n), where n is the length of the array, since we iterate through the array twice.
Space Complexity: O(1), no extra space is used apart from variables to store sums.
1def minimumAverageDifference(nums):
2 total_sum = sum(nums)
3 left_sum = 0
4 min_diff = float('inf')
5 min_index = 0
6
7 for i in range(len(nums)):
8 left_sum += nums[i]
9 left_avg = left_sum // (i + 1)
10 right_avg = 0 if i == len(nums) - 1 else (total_sum - left_sum) // (len(nums) - i - 1)
11 avg_diff = abs(left_avg - right_avg)
12 if avg_diff < min_diff:
13 min_diff = avg_diff
14 min_index = i
15
16 return min_index
17
18nums = [2, 5, 3, 9, 5, 3]
19print(minimumAverageDifference(nums))
This Python solution computes prefix sums while iterating over the list, and simultaneously evaluates the absolute difference between left and right averages at each index.
This approach involves calculating total sum ahead of time and using a running sum in-place as we iterate through the array, allowing avoidance of additional space for prefix sums.
By subtracting the running sum from the total sum, we derive the right sum efficiently. Use these sums to calculate averages and determine minimal average difference efficiently.
Time Complexity: O(n)
Space Complexity: O(1)
1
In this approach, instead of explicitly creating a prefix sum array, we modify the running total inline during the loop, making it both time- and space-efficient.