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