Minimum Operations to Make Array Equal - Problem
You start with a special array where each element follows the pattern arr[i] = (2 * i) + 1. This creates an array of consecutive odd numbers: [1, 3, 5, 7, 9, ...].
Your goal is to make all elements equal using the minimum number of operations. In each operation, you can:
- Choose any two indices
xandy - Subtract 1 from
arr[x] - Add 1 to
arr[y]
This is essentially redistributing values between array elements. The total sum remains constant, but you're trying to balance the array perfectly.
Example: For n = 3, the array is [1, 3, 5]. The target value is 3 (average), so you need 2 operations to transform it to [3, 3, 3].
Input & Output
example_1.py โ Small Array
$
Input:
n = 3
โบ
Output:
2
๐ก Note:
Array is [1, 3, 5]. Target is 3. Element 1 needs +2, element 5 gives -2. Total: 2 operations.
example_2.py โ Even Length
$
Input:
n = 6
โบ
Output:
9
๐ก Note:
Array is [1, 3, 5, 7, 9, 11]. Target is 6. Left half deficits: 5+3+1 = 9 operations needed.
example_3.py โ Single Element
$
Input:
n = 1
โบ
Output:
0
๐ก Note:
Array is [1]. Already equal, no operations needed.
Constraints
- 1 โค n โค 104
-
Array elements follow the pattern
arr[i] = (2 * i) + 1 - All elements can be made equal using the given operations
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Tanks have levels 1, 3, 5, 7, ... (consecutive odd numbers)
2
Target Level
All tanks should reach level n (the middle value)
3
Transfer Operations
Left tanks need water, right tanks provide it
4
Minimum Operations
Sum of all deficits = nยฒ/4 transfers needed
Key Takeaway
๐ฏ Key Insight: The array is perfectly symmetric around its middle value n, so we only need to calculate how much the first half is 'short' and that equals our minimum operations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code