You are given an integer array, nums, and an integer k. nums comprises of only 0’s and 1’s. In one move, you can choose two adjacent indices and swap their values.
Return the minimum number of moves required so that nums has k consecutive 1’s.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intminMoves(vector<int>& nums, int k){ vector<long> psum{0}; for(int i = 0; i < nums.size(); i++) if(nums[i]) psum.push_back(psum.back() + i); long res = INT_MAX; for(int i = 0; i < psum.size() - k; i++) { res = min(res, psum[i] + psum[i+k] - psum[i+k/2] - psum[i+(k+1)/2]); } return res - (k/2) * ((k+1)/2); } };