Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Using prefix sums
To solve the problem of making a binary string s
monotone increasing with the minimum number of flips, we can use dynamic programming and prefix counting:
- Count Prefix Sums:
- Maintain two variables,
flips_0_to_1
andflips_1_to_0
, which represent the minimum flips required to make the string monotone increasing by considering the characters0
and the characters1
. - Iterate through each character of the string
s
.
- Maintain two variables,
- Transitions:
- For each character:
- If it is
'0'
, then any1
before it needs to be flipped to0
. - If it is
'1'
, then add the minimum of currentflips_0_to_1
(keeping1
as1
) orflips_1_to_0
(flipping0
to1
).
- If it is
- For each character:
- Final Result:
- The final result will be the minimum value between
flips_0_to_1
andflips_1_to_0
after iterating through the string.
- The final result will be the minimum value between
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the strings
. This is because we perform constant-time operations for each character in the string. - 🧺 Space complexity:
O(1)
, since we are only using a constant amount of extra space for the variablesflips_0_to_1
andflips_1_to_0
.