处理前缀1的个数,遍历每种符合单调递增的情况,记录修改最小值
class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
n, pre, ans = len(s), [int(s[0])], len(s)
for i in range(1, n): pre.append(pre[-1] + int(s[i]))
for i in range(n):
ans = min(ans, pre[i] + (n - 1 - i - (pre[-1] - pre[i])))
ans = min(ans, n - pre[-1])
return ans