-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path3675.minimum-swaps-to-group-all-1s-together.cpp
81 lines (75 loc) · 1.38 KB
/
3675.minimum-swaps-to-group-all-1s-together.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Tag: Sliding Window, Array
// Time: O(N)
// Space: O(1)
// Ref: Leetcode-1151
// Note: -
// In this problem there is a binary array (contains only 0 and 1).
// You can swap arbitrary elements of the array.
//
// Now you need to combine all 1s in the array.
// Returns the minimum number of swaps required for a combination.
//
// **Example 1**
//
// Input:
//
// ```plaintext
// [1,0,1,0,1]
// ```
//
// Explanation:
//
// `[1,1,1,0,0]` or `[0,0,1,1,1]` only need one swap.
//
// Output:
//
// ```plaintext
// 1
// ```
//
// **Example 2**
//
// Input:
//
// ```plaintext
// [1,0,1,0,1,0,1,1,0,1]
// ```
//
// Output:
//
// ```plaintext
// 2
// ```
//
// Explanation:
//
// `[0,0,0,0,1,1,1,1,1,1]` requires only two swaps.
//
//
class Solution {
public:
/**
* @param arr: the binary array
* @return: the minimal number of swaps
*/
int minSwaps(vector<int> &arr) {
// write your code here
int n = arr.size();
int k = 0;
for (int x: arr) {
k += x;
}
int count = 0;
int ones = 0;
for (int i = 0; i < n; i++) {
if (i >= k) {
count -= arr[i - k];
}
count += arr[i];
if (i >= k - 1) {
ones = max(ones, count);
}
}
return k - ones;
}
};