Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 926. Flip String to Monotone Increasing

Rain Hu

926. 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 0 to 1 or from 1 to 0.
Return the minimum number of flips to make s monotone increasing.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

if (s[i] == '1') {
    dp[0][i] = dp[0][i-1] + 1;
    dp[1][i] = min(dp[0][i-1], dp[1][i-1]);
} else {
    dp[0][i] = dp[0][i-1];
    dp[1][i] = min(dp[0][i-1], dp[1][i-1]) + 1;
}

三、解題

1. DP

int minFlipsMonoIncr(string s) {
    int n = s.length();
    vector<vector<int>> dp(2, vector<int>(n, 0));
    if (s[0] == '0') 
        dp[1][0] = 1;
    else
        dp[0][0] = 1;
    for (int i = 1; i < n; i++) {
        if (s[i] == '1') {
            dp[0][i] = dp[0][i-1] + 1;                  // 將 1 翻成 0
            dp[1][i] = min(dp[0][i-1], dp[1][i-1]);
        } else {
            dp[0][i] = dp[0][i-1];
            dp[1][i] = min(dp[0][i-1], dp[1][i-1]) + 1; // 將 0 翻成 1
        }
    }
    return min(dp[0][n-1], dp[1][n-1]);
}

1. DP(space optimized)

int minFlipsMonoIncr(string s) {
    int n = s.length();
    int zero = 0;
    int one = 0;
    if (s[0] == '0') 
        one = 1;
    else
        zero = 1;
    for (int i = 1; i < n; i++) {
        if (s[i] == '1') {
            one = min(zero, one);
            zero++;
        } else {
            one = min(zero, one) + 1;
        }
    }
    return min(zero, one);
}

回目錄 Catalog


Share this post on:

Previous
[IT] C# Depth Ch.1 與時俱進的語言
Next
[IT] Shell 筆記