LC 1674. Minimum Moves to Make Array Complementary (差分)

link

class Solution {
public:
    int minMoves(vector<int>& nums, int limit) {
        int n=nums.size();
        vector<int> diff(2*limit+2);
        for(int i=0;i<n/2;i++){
            int a=nums[i];
            int b=nums[n-1-i];
            if(a>b) swap(a,b);
            if(a>=2){
                diff[2]+=2;
                diff[a+1]-=2;
            }
            diff[a+1]+=1;
            diff[a+b]-=1;
            diff[a+b+1]+=1;
            diff[b+limit+1]-=1;
            diff[b+limit+1]+=2;
            diff[2*limit+1]-=2;
        }
        int res=INT_MAX;
        for(int i=2;i<=2*limit;i++){
            diff[i]+=diff[i-1];
            res=min(res,diff[i]);
        }
        return res;
    }
};
posted @ 2020-11-30 16:14  feibilun  阅读(98)  评论(0编辑  收藏  举报