[LeetCode] Minimum Moves to Make Array Complementary

1674. Minimum Moves to Make Array Complementary

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 nums complementary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minMoves(vector<int>& nums, int limit) {
vector<int> mark((limit + 1)<<1, 0);
int sz = nums.size(), half = sz>>1;
mark[0] = sz;
for(int i = 0; i < half; i++) {
int sum = nums[i] + nums[sz - i - 1];
mark[min(nums[i], nums[sz - i - 1]) + 1] -= 1;
mark[sum] -= 1;
mark[sum + 1] += 1;
mark[max(nums[i], nums[sz - i - 1]) + limit + 1] += 1;
}
int res = mark[0];
for(int i = 1; i < mark.size(); i++) {
res = min(res, mark[i] += mark[i - 1]);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/27/PS/LeetCode/minimum-moves-to-make-array-complementary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.