![]() |
VOOZH | about |
Given an integer array arr[] of size n, the task is to return the index with minimum average difference. The average difference of index i is the absolute difference between the average of the first i + 1 elements of arr[] and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.
Note: If there are multiple such indices, return the smallest one.
Examples:
Input: arr[] = {2, 5, 3, 9, 5, 3}
Output: 3
Explanation:
- For i = 0, average of first element = 2 and average of remaining elements = (5 + 3 + 9 + 5 + 3)/5 = 5, so absolute difference = 3.
- For i = 1, average of first 2 elements = floor(3.5) = 3 and average of remaining elements = (3 + 9 + 5 + 3)/4 = 5, so absolute difference = 2.
- For i = 2, average of first 3 elements = floor(3.33) = 3 and average of remaining elements = (9 + 5 + 3)/3 = floor(5.66) = 5, so absolute difference = 2.
- For i = 3, average of first 4 elements = floor(4.75) = 4, and average of remaining elements = (5 + 3)/2 = 4, so absolute difference = 0.
- For i = 4, average of first 5 elements = floor(4.8) = 4, and average of remaining elements = 3, so absolute difference = 1.
- For i = 5, average of first 6 elements = floor(4.5) = 4, and average of remaining elements = 0, so absolute difference = 4.
The smallest absolute difference is at index = 3.
Input: arr[] = {0}
Output: 0
Explanation: Minimum absolute difference is at index 0 = 0 - 0 = 0.
Approach: To solve the problem, follow the below idea:
Iterate over all the indices and maintain the running sum for first i + 1 elements, say prefSum and last n - i - 1 elements, say suffSum. Initialize prefSum = 0 and suffSum = sum of all elements in array. Now for every element, add it to prefSum and subtract it from suffSum. Calculate the absolute difference between the average of prefSum and suffSum and return the minimum absolute difference.
Step-by-step algorithm:
Below is the implementation of the above algorithm:
3
Time Complexity: O(N), where N is the number of elements in arr[].
Space Complexity: O(1)