926. Flip String to Monotone Increasing(DP)

This is a typical dp question.

Monotonic increasing only has three patterns, 000111, 0000 and 1111.

In brute force, we just need to calculate a prefix sum for 0 and 1.

We use a mid-point to find the minimum flip, the left-hand side of the mid-point should be all 0, so the cost would be the prefix sum of 1, and vice-versa for the right-hand side.

class Solution {
public:
    int minFlipsMonoIncr(string s) {
        int n = s.length();
        vector<int> f0(n + 1, 0);
        vector<int> f1(n + 1, 0);
        for(int i = 1; i <= n; i++){
            f0[i] = f0[i - 1] + (s[i - 1] == '1');
        }
        for(int i = n - 1; i >= 0; i--){
            f1[i] = f1[i + 1] + (s[i] == '0');
        }
        int res = INT_MAX;
        for(int i = 0; i <= n; i++){
            res = min(res, f0[i] + f1[i]);
        }
        return res;
    }
};

Actually, the space complexity can be reduced to O(1).

The logic is that we can either flip 0 to 1 or 1 to 0.
If we loop the array from left to right.

We can choose to flip the zero that shows up after the one or flips all the ones before the zero.

of course, we gonna choose the minimum one. Also, because if there is no one showed up ever, we do not need to consider fliping the zero to one.

class Solution {
public:
    int minFlipsMonoIncr(string s) {
        int cnt=0;
        int flip=0;
        for(auto i:s)
        {
            if(i=='0')
                flip++;
            else
                cnt++;
            flip=min(flip,cnt);
        }
        return flip;
        
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值