class Solution:
def minOperations(self, n: int) -> int:
# The array will be [1, 3, 5, ..., 2n-1]
# The target value is n
# The minimal number of moves is sum(abs(arr[i] - n)) for i in range(n)
# This simplifies to n^2 // 4
return (n * n) // 4
class Solution {
public:
int minOperations(int n) {
// The minimal number of moves is n^2 / 4
return (n * n) / 4;
}
};
class Solution {
public int minOperations(int n) {
// The minimal number of moves is n^2 / 4
return (n * n) / 4;
}
}
var minOperations = function(n) {
// The minimal number of moves is n^2 / 4
return Math.floor(n * n / 4);
};
You are given an integer n
. Consider an array arr
of length n
where arr[i] = 2 * i + 1
for 0 ≤ i < n
. In other words, the array contains the first n
odd numbers: [1, 3, 5, ..., 2n-1]
.
In one operation, you can choose any two indices and increase the value at one index by 1 while decreasing the value at the other index by 1. Your goal is to make all elements in the array equal using the minimum number of such operations.
Return the minimum number of operations required to make all elements of arr
equal.
At first glance, it seems we might need to simulate the process, repeatedly picking the largest and smallest elements and adjusting them until all values are equal. However, this would be inefficient for large n
.
By observing the problem, we notice that:
n
for this construction.n
directly.
n
.
n
, calculate how much it needs to be increased. For each element greater than n
, calculate how much it needs to be decreased. Since the array is symmetric, we only need to consider one side.
arr[i]
and n
for all i
less than n//2
.
n^2 // 4
.
This approach is efficient and avoids unnecessary simulation.
Let's use n = 5
as an example. The array is [1, 3, 5, 7, 9]
. The target value is 5
.
arr[0] = 1
needs 4
moves to reach 5
arr[1] = 3
needs 2
moves to reach 5
arr[2] = 5
is already at the targetarr[3] = 7
needs 2
moves to reduce to 5
arr[4] = 9
needs 4
moves to reduce to 5
Since each operation transfers 1 unit from a high value to a low value, we only need to sum the moves for one side:
4 + 2 = 6
moves (for indices 0 and 1).
The formula gives n^2 // 4 = 25 // 4 = 6
, which matches our calculation.
The key insight is recognizing the symmetry and arithmetic properties of the array. By realizing that the number of operations only depends on the array length and not the actual values, we avoid unnecessary simulation. The elegant formula n^2 // 4
provides an optimal, constant-time solution.