[leetcode]926. Flip String to Monotone Increasing

本文介绍如何使用动态规划解决LeetCode 926题,即如何通过最少次数的字符翻转使由'0'和'1'组成的字符串变为单调递增。算法将问题分解为两个子问题,从左到右翻转'1'至'0',从右到左翻转'0'至'1',并求最小值。

[leetcode]926. Flip String to Monotone Increasing


Analysis

waiting~—— [每天刷题并不难0.0]

A string of '0’s and '1’s is monotone increasing if it consists of some number of '0’s (possibly 0), followed by some number of '1’s (also possibly 0.)
We are given a string S of '0’s and '1’s, and we may flip any ‘0’ to a ‘1’ or a ‘1’ to a ‘0’.
Return the minimum number of flips to make S monotone increasing.
在这里插入图片描述
动态规划,把输入分割成两部分,第一部分是从左往右的把‘1’变成‘0’,第二部分是从右往左的把‘0’变成‘1’,然后求最小值。

Implement

class Solution {
public:
    int minFlipsMonoIncr(string S) {
        int len = S.size();
        int res = INT_MAX;
        vector<int> dp0(len+1, 0);
        vector<int> dp1(len+1, 0);
        for(int i=0; i<len; i++)
            dp0[i+1] += dp0[i]+(S[i]=='0'?0:1);
        for(int i=len; i>0; i--)
            dp1[i-1] += dp1[i]+(S[i-1]=='1'?0:1);
        for(int i=0; i<=len; i++)
            res = min(res, dp0[i]+dp1[i]);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值