[LeetCode] Minimum Adjacent Swaps for K Consecutive Ones

1703. Minimum Adjacent Swaps for K Consecutive Ones

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
class Solution {
public:
int minMoves(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);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/07/PS/LeetCode/minimum-adjacent-swaps-for-k-consecutive-ones/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.