# 926. Flip String to Monotone Increasing [Medium]

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

A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)

We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.

Return the minimum number of flips to make S monotone increasing.

Example 1:

Input: "00110"
Output: 1
Explanation: We flip the last digit to get 00111.


Example 2:

Input: "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.


Example 3:

Input: "00011000"
Output: 2
Explanation: We flip to get 00000000.


Note:

1. 1 <= S.length <= 20000
2. S only consists of '0' and '1' characters.

### 算法思路：

class Solution {
public:
int minFlipsMonoIncr(string S) {
int n = S.size();
int numbOf1 = 0;
int numbOf0 = 0;
int res = 0;
for (int i = 0; i < n; i++) {
if (S[i] == '1') numbOf1++;
else numbOf0++;
// flip those ones to zeros cause it is cheaper
if (numbOf0 > numbOf1) {
res += numbOf1;
numbOf1 = 0;
numbOf0 = 0;
}
}
return res + numbOf0;
}
};

• dp[i]：表示处于位置i的时候，保证0-1字符串非单减需要的最少转换操作数
• S[i] == '1'，直接加到numbOf1，dp[i] = dp[i - 1] ，S[i] == '0'保持不变则前面的1都要变成0，0变成1，那么转化步骤+1
• 这里简化了dp维度，使空间复杂度将为O(1)
// dp[0] = 0
// dp[i] = dp[i - 1]             (S[i] == '1')
//       = min(numbOf1, dp + 1)  (S[i] == '0')
class Solution {
public:
int minFlipsMonoIncr(string S) {
int n = S.size();
int numbOf1 = 0;
int dp = 0;
for (int i = 0; i < n; i++) {
if (S[i] == '1') numbOf1++; // dp = dp is not necessary to write it!
else dp = min(numbOf1, dp + 1);
}
return dp;
}
};

### 参考资料：

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

cainiao_23333

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

09-01 74
04-04 161
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客