给定一个由 0 和 1 组成的序列 A ,问至少翻转多少个 0 和 1 使得该序列前部分都是 0 后部分都是 1.
思路:枚举0和1的分界点,代价可以O(1)的算出来,只需要预处理出序列A中一开始有几个0即可,代价就是当前扫过的1的个数加上后面的0的个数
class Solution {
public:
int minFlipsMonoIncr(string S) {
int len = S.length();
int zoro=0,one=0;
for(int i = 0; i < len; i++){
if(S[i]=='0') zoro++;
}
int ans = min(9999999,one+zoro);
for(int i = 0; i <len; i++)
{
if(S[i]=='0') zoro--;
else one++;
ans=min(ans,zoro+one);
}
return ans;
}
};