You are given an integer array nums of even length n and an integer
limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive.
The array nums is complementary if for all indices i (0-indexed),
nums[i] + nums[n - 1 - i] equals the same number. For example, the array
[1,2,3,4] is complementary because for all indices i, nums[i] + nums[n -1 - i] = 5.
Return the _minimum number of moves required to make _numscomplementary.
Input: nums =[1,2,4,3], limit =4Output: 1Explanation: In 1 move, you can change nums to [1,2,_2_ ,3](underlined elements are changed).nums[0]+ nums[3]=1+3=4.nums[1]+ nums[2]=2+2=4.nums[2]+ nums[1]=2+2=4.nums[3]+ nums[0]=3+1=4.Therefore, nums[i]+ nums[n-1-i]=4for every i, so nums is complementary.
Input: nums =[1,2,2,1], limit =2Output: 2Explanation: In 2 moves, you can change nums to [_2_ ,2,2,_2_]. You cannot change any number to 3 since 3> limit.
For each pair (nums[i], nums[n-1-i]), the sum can be made complementary by changing either or both numbers. By analyzing the cost to make each pair sum to every possible target, we can efficiently find the minimum moves using a prefix sum sweep.
classSolution {
public:int minMoves(vector<int>& nums, int limit) {
int n = nums.size(), ans = INT_MAX;
vector<int> diff(2* limit +2);
for (int i =0; i < n /2; ++i) {
int a = nums[i], b = nums[n -1- i];
diff[2] +=2;
diff[min(a, b) +1] -=1;
diff[a + b] -=1;
diff[a + b +1] +=1;
diff[max(a, b) + limit +1] +=1;
}
int curr =0;
for (int s =2; s <=2* limit; ++s) {
curr += diff[s];
ans = min(ans, curr);
}
return ans;
}
};
classSolution {
funminMoves(nums: IntArray, limit: Int): Int {
val n = nums.size
val diff = IntArray(2 * limit + 2)
for (i in0 until n / 2) {
val a = nums[i]
val b = nums[n - 1 - i]
diff[2] +=2 diff[minOf(a, b) + 1] -=1 diff[a + b] -=1 diff[a + b + 1] +=1 diff[maxOf(a, b) + limit + 1] +=1 }
var ans = n
var curr = 0for (s in2..2 * limit) {
curr += diff[s]
ans = minOf(ans, curr)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defminMoves(self, nums: list[int], limit: int) -> int:
n: int = len(nums)
diff: list[int] = [0] * (2* limit +2)
for i in range(n //2):
a, b = nums[i], nums[n -1- i]
diff[2] +=2 diff[min(a, b) +1] -=1 diff[a + b] -=1 diff[a + b +1] +=1 diff[max(a, b) + limit +1] +=1 ans: int = n
curr: int =0for s in range(2, 2* limit +1):
curr += diff[s]
ans = min(ans, curr)
return ans