반응형
https://leetcode.com/problems/flip-string-to-monotone-increasing/description/
Flip String to Monotone Increasing - LeetCode
Flip String to Monotone Increasing - A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none). You are given a binary string s. You can flip s[i] changing it from 0 to
leetcode.com
바이너리 스트링을 최소 횟수로 증가하는 형태로 만들어주어야합니다.
스트링을 순차적으로 탐색하면서 1이 나오는 횟수를 구해줍니다.
0일 때는, 지금까지의 1을 0으로 flip 했을 때의 횟수(지금까지 1이 나온 횟수)와 지금의 0을 1로 flip했을 때의 횟수 중,
더 작은 값을 현재까지의 최소 횟수에 업데이트해줍니다.
class Solution {
public:
int minFlipsMonoIncr(string s) {
int res = 0, cnt = 0;
for(char c : s) {
if(c == '0') res = min(cnt, ++res);
else cnt++;
}
return res;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 93 : Restore IP Addresses (0) | 2023.01.21 |
---|---|
LeetCode 491 : Non-decreasing Subsequences (0) | 2023.01.20 |
LeetCode 918 : Maximum Sum Circular Subarray (0) | 2023.01.19 |
LeetCode 2421 : Number of Good Paths (0) | 2023.01.15 |
LeetCode 1061 : Lexicographically Smallest Equivalent String (0) | 2023.01.14 |