Skip to main content
Back to problems
#1422
Easy Algorithms

Maximum score after splitting a string

String Prefix Sum
65.1% acceptance
Feb 25, 2026
2186
91
Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_score(s: String) -> i32 {
    let s: Vec<u8> = s.bytes().collect();
    let n = s.len();
    let total_ones: i32 = s.iter().filter(|&&b| b == b'1').count() as i32;
    let mut zeros = 0i32;
    let mut ones_right = total_ones;
    let mut best = 0;
    for i in 0..n-1 {
      if s[i] == b'0' { zeros += 1; } else { ones_right -= 1; }
      best = best.max(zeros + ones_right);
    }
    best
  }
}