Problem Description
Given a 0-indexed integer array nums, the task is to find an index i that minimizes the absolute difference between the average of the first i+1 elements and the average of the remaining n-i-1 elements. Both averages are computed using integer division (rounded down). If the index is the last element, the second average is considered 0. If there are multiple indices with the same minimum difference, return the smallest index.
Key Insights
- Use prefix sums to efficiently compute the sum of the subarrays.
- At each index, maintain a running sum to calculate the left part average.
- For the right part, use the total sum minus the current prefix sum.
- Carefully handle the case when there are no elements on the right by considering their average as 0.
- Iterate through the array once, leading to an optimal O(n) solution.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1) (ignoring the input storage)
Solution
The approach begins by computing the total sum of the array. As you iterate over the elements, maintain a running prefix sum. At each index, compute:
- left_average = prefix_sum / (i + 1) (using integer division)
- right_average = (total_sum - prefix_sum) / (n - i - 1) (if i is not the last index; otherwise, it is 0) Calculate the absolute difference between left_average and right_average and track the minimum difference encountered along with the corresponding index. Finally, return the index with the minimum average difference.