leetcode - 926. Flip String to Monotone Increasing

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)
  • 19
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值