1
+ // Runtime: 46 ms (Top 47.95%) | Memory: 20.1 MB (Top 15.69%)
1
2
class Solution {
2
3
public:
3
4
int minFlipsMonoIncr (string s) {
@@ -7,34 +8,34 @@ class Solution {
7
8
// for this maintain prefix and suffix
8
9
9
10
int n = s.size ();
10
- vector<int > noOfZerosToRight (n,0 ); // R to L
11
- vector<int > noOfOnesToLeft (n,0 ); // L to R
11
+ vector<int > noOfZerosToRight (n,0 ); // R to L
12
+ vector<int > noOfOnesToLeft (n,0 ); // L to R
12
13
13
- if (s[0 ] == ' 1' ) noOfOnesToLeft[0 ] = 1 ;
14
+ if (s[0 ] == ' 1' ) noOfOnesToLeft[0 ] = 1 ;
14
15
for (int i=1 ;i<n;i++){
15
16
if (s[i] == ' 1' ) noOfOnesToLeft[i] = noOfOnesToLeft[i-1 ] + 1 ;
16
17
else noOfOnesToLeft[i] = noOfOnesToLeft[i-1 ];
17
18
}
18
19
19
- if (s[n-1 ] == ' 0' ) noOfZerosToRight[n-1 ] = 1 ;
20
+ if (s[n-1 ] == ' 0' ) noOfZerosToRight[n-1 ] = 1 ;
20
21
for (int i=n-2 ;i>=0 ;i--){
21
22
if (s[i] == ' 0' ) noOfZerosToRight[i] = noOfZerosToRight[i+1 ] + 1 ;
22
23
else noOfZerosToRight[i] = noOfZerosToRight[i+1 ];
23
24
}
24
-
25
+
25
26
// starting treating i as partition of 0 and 1:
26
27
// 0 at the lefts and 1 at the rights including i:
27
28
int ans = 1e9 ;
28
29
for (int i=0 ;i<n;i++){
29
- int leftFlips = 0 ; // when we want all 1s
30
+ int leftFlips = 0 ; // when we want all 1s
30
31
int rightFlips = noOfZerosToRight[i];
31
-
32
+
32
33
if (i-1 >= 0 ) leftFlips = noOfOnesToLeft[i-1 ];
33
34
ans = min (ans, (leftFlips + rightFlips));
34
35
}
35
-
36
- ans = min (ans, noOfOnesToLeft.back () + 0 ); // when want all 0s
36
+
37
+ ans = min (ans, noOfOnesToLeft.back () + 0 ); // when want all 0s
37
38
return ans;
38
39
}
39
40
// O(N) + O(N)
40
- };
41
+ };
0 commit comments