[leetcode]926. Flip String to Monotone Increasing

[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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/84751550