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.
1#include <iostream>
2#include <vector>
3#include <climits>
4
5int minimumAverageDifference(std::vector<int>& nums) {
6 long long totalSum = 0, leftSum = 0;
7 int n = nums.size(), minIndex = 0;
8 for (int num : nums) totalSum += num;
9 long long minDiff = LLONG_MAX;
10 for (int i = 0; i < n; ++i) {
11 leftSum += nums[i];
12 long long leftAvg = leftSum / (i + 1);
13 long long rightAvg = (i == n - 1) ? 0 : (totalSum - leftSum) / (n - i - 1);
14 long long avgDiff = std::abs(leftAvg - rightAvg);
15 if (avgDiff < minDiff) {
16 minDiff = avgDiff;
17 minIndex = i;
18 }
19 }
20 return minIndex;
21}
22
23int main() {
24 std::vector<int> nums = {2,5,3,9,5,3};
25 std::cout << minimumAverageDifference(nums);
26 return 0;
27}
This C++ solution follows a similar approach with vectors. Prefix sums are calculated to derive the minimum average difference at each index efficiently.
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.