Skip to content

1422. Maximum Score After Splitting a String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int maxScore(string s) {
    int ans = 0;
    int zeros = 0;
    int ones = ranges::count(s, '1');

    for (int i = 0; i + 1 < s.size(); ++i) {
      if (s[i] == '0')
        ++zeros;
      else
        --ones;
      ans = max(ans, zeros + ones);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int maxScore(String s) {
    int ans = 0;
    int zeros = 0;
    int ones = (int) s.chars().filter(c -> c == '1').count();

    for (int i = 0; i + 1 < s.length(); ++i) {
      if (s.charAt(i) == '0')
        ++zeros;
      else
        --ones;
      ans = Math.max(ans, zeros + ones);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maxScore(self, s: str) -> int:
    ans = 0
    zeros = 0
    ones = s.count('1')

    for i in range(len(s) - 1):
      if s[i] == '0':
        zeros += 1
      else:
        ones -= 1
      ans = max(ans, zeros + ones)

    return ans