Skip to content

926. Flip String to Monotone Increasing 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int minFlipsMonoIncr(string s) {
    // the number of characters to be flilpped to make the substring so far
    // monotone increasing
    int dp = 0;
    int count1 = 0;

    for (const char c : s)
      if (c == '0')
        // 1. Flip '0'.
        // 2. Keep '0' and flip all the previous 1s.
        dp = min(dp + 1, count1);
      else
        ++count1;

    return dp;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int minFlipsMonoIncr(String s) {
    // the number of characters to be flilpped to make the substring so far
    // monotone increasing
    int dp = 0;
    int count1 = 0;

    for (final char c : s.toCharArray())
      if (c == '0')
        // 1. Flip '0'.
        // 2. Keep '0' and flip all the previous 1s.
        dp = Math.min(dp + 1, count1);
      else
        ++count1;

    return dp;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def minFlipsMonoIncr(self, s: str) -> int:
    # the number of characters to be flilpped to make the substring so far
    # monotone increasing
    dp = 0
    count1 = 0

    for c in s:
      if c == '0':
        # 1. Flip '0'.
        # 2. Keep '0' and flip all the previous 1s.
        dp = min(dp + 1, count1)
      else:
        count1 += 1

    return dp