---
# System prepended metadata

title: 926. Flip String to Monotone Increasing
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 926. Flip String to Monotone Increasing

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

## 題目
翻轉最少的字元並達到monotone increasing 回傳翻轉的字元數量
monotone increasing : Always not decreasing
## 程式碼 

```cpp=
class Solution {
public:
    int minFlipsMonoIncr(string s) {
        int n = s.size(), ans = n, ZeroCount = count(s.begin(), s.end(), '0');//目前位置右邊有多少0，初始化為所有0的數量
        for(int i = 0, OneCount = 0;i < n;i++){//目前位置左邊有多少1
            int temp = 0;//計算這個位置需要改變多少0和1
            temp += OneCount;
            (s[i] == '1') ? OneCount++ : ZeroCount--;
            temp += ZeroCount;
            if(temp < ans) ans = temp;//更新ans
        }
        return ans;
    }
};
```