LeetCode Solutions
926. Flip String to Monotone Increasing
Time: Space:
class Solution {
public:
int minFlipsMonoIncr(string S) {
vector<int> dp(2);
for (int i = 0; i < S.length(); ++i) {
int temp = dp[0] + (S[i] == '1');
dp[1] = min(dp[0], dp[1]) + (S[i] == '0');
dp[0] = temp;
}
return min(dp[0], dp[1]);
}
};
class Solution {
public int minFlipsMonoIncr(String S) {
int[] dp = new int[2];
for (int i = 0; i < S.length(); ++i) {
int temp = dp[0] + (S.charAt(i) == '1' ? 1 : 0);
dp[1] = Math.min(dp[0], dp[1]) + (S.charAt(i) == '0' ? 1 : 0);
dp[0] = temp;
}
return Math.min(dp[0], dp[1]);
}
}
class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
dp = [0] * 2
for i, c in enumerate(S):
dp[0], dp[1] = dp[0] + (c == '1'), min(dp[0], dp[1]) + (c == '0')
return min(dp[0], dp[1])