Minimum Average Difference - Problem

You are given a 0-indexed integer array nums of length n.

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

Note:

  • The absolute difference of two numbers is the absolute value of their difference.
  • The average of n elements is the sum of the n elements divided (integer division) by n.
  • The average of 0 elements is considered to be 0.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,5,3,9,5,3]
Output: 3
💡 Note: At index 3: left = [2,5,3,9] (avg=4), right = [5,3] (avg=4), difference = 0 (minimum possible)
Example 2 — Single Element
$ Input: nums = [0]
Output: 0
💡 Note: Only one element, so left avg = 0, right avg = 0 (no right elements), difference = 0
Example 3 — Two Elements
$ Input: nums = [2,8]
Output: 0
💡 Note: Index 0: left avg = 2, right avg = 8, diff = 6. Index 1: left avg = 5, right avg = 0, diff = 5. Choose index 1

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Minimum Average Difference Problem253953012345Left: [2,5,3,9]Right: [5,3]Avg = 19/4 = 4Avg = 8/2 = 4Difference = |4 - 4| = 0Output: Index 3 (minimum difference)
Understanding the Visualization
1
Input Array
Given array [2,5,3,9,5,3] with indices 0-5
2
Calculate Differences
For each index, find |left_avg - right_avg|
3
Output Index
Return index with minimum difference
Key Takeaway
🎯 Key Insight: Use prefix sums to efficiently calculate left and right averages without recalculation
Asked in
Amazon 12 Microsoft 8
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen