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.
1import java.util.*;
2
3class Solution {
4 public int minimumAverageDifference(int[] nums) {
5 long totalSum = 0, leftSum = 0;
6 int n = nums.length, minIndex = 0;
7 for (int num : nums) totalSum += num;
8 long minDiff = Long.MAX_VALUE;
9 for (int i = 0; i < n; ++i) {
10 leftSum += nums[i];
11 long leftAvg = leftSum / (i + 1);
12 long rightAvg = (i == n - 1) ? 0 : (totalSum - leftSum) / (n - i - 1);
13 long avgDiff = Math.abs(leftAvg - rightAvg);
14 if (avgDiff < minDiff) {
15 minDiff = avgDiff;
16 minIndex = i;
17 }
18 }
19 return minIndex;
20 }
21
22 public static void main(String[] args) {
23 Solution sol = new Solution();
24 int[] nums = {2,5,3,9,5,3};
25 System.out.println(sol.minimumAverageDifference(nums));
26 }
27}
In Java, we similarly calculate prefix sums using primitive long data types for sums to avoid overflow, ensuring constant time calculation for averages at each step.
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.