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.
1function minimumAverageDifference(nums) {
2 let totalSum = nums.reduce((a, b) => a + b, 0);
3 let leftSum = 0;
4 let minDiff = Number.MAX_VALUE;
5 let minIndex = 0;
6
7 for (let i = 0; i < nums.length; i++) {
8 leftSum += nums[i];
9 const leftAvg = Math.floor(leftSum / (i + 1));
10 const rightAvg = i === nums.length - 1 ? 0 : Math.floor((totalSum - leftSum) / (nums.length - i - 1));
11 const avgDiff = Math.abs(leftAvg - rightAvg);
12
13 if (avgDiff < minDiff) {
14 minDiff = avgDiff;
15 minIndex = i;
16 }
17 }
18
19 return minIndex;
20}
21
22const nums = [2, 5, 3, 9, 5, 3];
23console.log(minimumAverageDifference(nums));
In JavaScript, this solution calculates prefix sums and absolute differences efficiently using array methods like reduce for the total sum. We use integer division with Math.floor.
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.