[LeetCode] Minimum Swaps to Group All 1`s Together II

2134. Minimum Swaps to Group All 1’s Together II

A swap is defined as taking two distinct positions in an array and swapping the values in them.

A circular array is defined as an array where we consider the first element and the last element to be adjacent.

Given a binary circular array nums, return the minimum number of swaps required to group all 1’s present in the array together at any location.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minSwaps(vector<int>& A) {
int res = INT_MAX, count = accumulate(begin(A), end(A), 0), n = A.size();
for(int i = 0, window = 0; i < 2 * n; i++) {
if(A[i % n]) window++;
if(i >= count and A[(i - count + n) % n]) window--;
if(i >= count - 1) {
res = min(res, count - window);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/06/PS/LeetCode/minimum-swaps-to-group-all-1s-together-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.