Skip to content

Commit e11c362

Browse files
committed
Leetcode 926 Flip String to Monotone Increasing
1 parent ec3fd86 commit e11c362

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed
Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,24 @@
1-
t st
1+
class Solution {
2+
public int minFlipsMonoIncr(String s) {
3+
int n = s.length();
4+
int[] l = new int[n];
5+
int[] r = new int[n];
6+
l[0] = s.charAt(0) == '0' ? 0 : 1;
7+
r[n-1] = s.charAt(n-1) == '1' ? 0 : 1;
8+
9+
for(int i=1;i<n;i++) {
10+
l[i] = s.charAt(i) == '1' ? l[i-1] + 1 : l[i-1];
11+
}
12+
13+
for(int i=n-2;i>=0;i--) {
14+
r[i] = s.charAt(i) == '0' ? r[i+1] + 1 : r[i+1];
15+
}
16+
17+
// the case all 0s or 1s
18+
int ans = Math.min(r[0], l[n-1]);
19+
for(int i=1;i<n;i++) {
20+
ans = Math.min(ans, l[i-1] + r[i]);
21+
}
22+
return ans;
23+
}
24+
}

0 commit comments

Comments
 (0)