File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments