Flip String to Monotone Increasing

https://leetcode.cn/problems/flip-string-to-monotone-increasing/

def minFlipsMonoIncr(self, s: str) -> int:
        # n0: 统计当前字符的右边还有多少个0需要被置为1
        # n1: 统计当前字符的左边还有多少个1需要被置为0
        n = len(s)
        n0 = s.count("0")
        n1 = 0 
        res = n - n0

        for i in range(n):
            if s[i] == "0":                     # 当前字符是0时,不需要更新结果
                n0 -= 1
            else:
                res = min(n0 + n1, res)         # 当前字符是1时,将左边的所有的0置为1(n1),右边所有的1置为0(n0),更新结果
                n1 += 1
        
        return res
posted @ 2022-11-06 19:35  7aughing  阅读(16)  评论(0编辑  收藏  举报