-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2134.cpp
More file actions
27 lines (26 loc) · 717 Bytes
/
2134.cpp
File metadata and controls
27 lines (26 loc) · 717 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int minSwaps(vector<int>& nums) {
int n = nums.size();
int oneCnt = 0;
for (auto& num : nums) {
if (num)
oneCnt += 1;
}
if (oneCnt == 0) return 0;
int currentOneCnt = 0;
for (int i = 0; i < oneCnt - 1; ++i) {
if (nums[i])
currentOneCnt += 1;
}
int res = INT_MAX;
for (int i = oneCnt - 1; i < n + oneCnt - 1; ++i) {
if (nums[i % n])
currentOneCnt += 1;
res = min(res, oneCnt - currentOneCnt);
if (nums[(i - oneCnt + 1) % n])
currentOneCnt -= 1;
}
return res;
}
};