程式語言 - LeetCode - C++ - 1674. Minimum Moves to Make Array Complementary



參考資訊:
https://github.com/sarvex/leetcode-rockstar/blob/main/solution/1600-1699/1674.Minimum%20Moves%20to%20Make%20Array%20Complementary/README.md

題目:


解答:

class Solution {
public:
    int minMoves(vector<int>& nums, int limit) {
        int n = nums.size();
        vector<int> d(2 * limit + 2, 0);

        for (int i = 0; i < (n >> 1); ++i) {
            int a = nums[i];
            int b = nums[n - i - 1];

            if (a > b) {
                swap(a, b);
            }

            d[2] += 2;
            d[a + 1] -= 1;
            d[a + b] -= 1;
            d[a + b + 1] += 1;
            d[b + limit + 1] += 1;
        }

        int ans = INT_MAX;
        int cnt = 0;

        for (int i = 2; i <= (limit << 1); ++i) {
            cnt += d[i];
            ans = min(ans, cnt);
        }

        return ans;
    }
};