Skip to content

Commit 42efe97

Browse files
authored
Create 2134. Minimum Swaps to Group All 1's Together II (#544)
2 parents 5200410 + 4d58693 commit 42efe97

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
int minSwaps(vector<int>& nums) {
4+
int n = nums.size();
5+
int totalOnes = 0;
6+
7+
for (int num : nums) {
8+
if (num == 1) {
9+
totalOnes++;
10+
}
11+
}
12+
13+
if (totalOnes == 0 || totalOnes == n) {
14+
return 0;
15+
}
16+
17+
int maxOnesInWindow = 0;
18+
int currentOnesInWindow = 0;
19+
20+
for (int i = 0; i < totalOnes; i++) {
21+
if (nums[i] == 1) {
22+
currentOnesInWindow++;
23+
}
24+
}
25+
26+
maxOnesInWindow = currentOnesInWindow;
27+
28+
for (int i = 1; i < n; i++) {
29+
if (nums[i - 1] == 1) {
30+
currentOnesInWindow--;
31+
}
32+
if (nums[(i + totalOnes - 1) % n] == 1) {
33+
currentOnesInWindow++;
34+
}
35+
maxOnesInWindow = std::max(maxOnesInWindow, currentOnesInWindow);
36+
}
37+
38+
return totalOnes - maxOnesInWindow;
39+
}
40+
};

0 commit comments

Comments
 (0)