Minimum Operations to Make Array Equal - Problem
You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.
Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.
Input & Output
Example 1 — Even Length Array
$
Input:
n = 3
›
Output:
2
💡 Note:
Array is [1,3,5]. Target is 3. Element 1 needs +2, element 5 has excess 2. Operations: 2.
Example 2 — Larger Even Array
$
Input:
n = 6
›
Output:
9
💡 Note:
Array is [1,3,5,7,9,11]. Target is 6. Excess from second half: (7-6)+(9-6)+(11-6) = 1+3+5 = 9.
Example 3 — Single Element
$
Input:
n = 1
›
Output:
0
💡 Note:
Array is [1]. Only one element, already equal. No operations needed.
Constraints
- 1 ≤ n ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array [1,3,5,7,9,11] with n=6
2
Target Value
All elements should become 6 (middle value)
3
Operations Needed
Count moves from excess to deficit: 9 operations
Key Takeaway
🎯 Key Insight: The target is always the middle value n, and we only need to sum the excess from the upper half
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code