Description
A binary string is monotone increasing if it consists of some number of 0’s (possibly none), followed by some number of 1’s (also possibly none).
You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.
Return the minimum number of flips to make s monotone increasing.
Example 1:
Input: s = "00110"
Output: 1
Explanation: We flip the last digit to get 00111.
Example 2:
Input: s = "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.
Example 3:
Input: s = "00011000"
Output: 2
Explanation: We flip to get 00000000.
Constraints:
1 <= s.length <= 10^5
s[i] is either '0' or '1'.
Solution
Dynamic programming, dp_0
is the minimum number of flips to end with 0
, and dp_1
is the number of ending with 1
, then:
d p 0 = { d p 0 , if s[i] is 0 d p 0 + 1 , if s[i] is 1 d p 1 = { 1 + min ( d p 0 , d p 1 ) , if s[i] is 0 min ( d p 1 , d p 0 ) , if s[i] is 1 \begin{aligned} &dp_0=\begin{cases} dp_0, &\text{if s[i] is 0}\\ dp_0+1, &\text{if s[i] is 1} \end{cases} \\ &dp_1=\begin{cases} 1 + \min(dp_0, dp_1), &\text{if s[i] is 0}\\ \min(dp_1, dp_0), &\text{if s[i] is 1} \end{cases} \end{aligned} dp0={dp0,dp0+1,if s[i] is 0if s[i] is 1dp1={1+min(dp0,dp1),min(dp1,dp0),if s[i] is 0if s[i] is 1
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
Code
class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
dp_0, dp_1 = 1 if s[0] == '1' else 0, 1 if s[0] == '0' else 0
for each_c in s[1:]:
if each_c == '0':
dp_0, dp_1 = dp_0, 1 + min(dp_0, dp_1)
elif each_c == '1':
dp_0, dp_1 = 1 + dp_0, min(dp_0, dp_1)
return min(dp_0, dp_1)