1. 程式人生 > >[leetcode]926. Flip String to Monotone Increasing

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