Maximum Score After Splitting a String - Problem

Given a string s consisting of zeros and ones only, return the maximum score after splitting the string into two non-empty substrings (left substring and right substring).

The score is calculated as:

  • Number of zeros in the left substring
  • Plus number of ones in the right substring

Both substrings must be non-empty after the split.

Input & Output

Example 1 — Basic Case
$ Input: s = "011101"
Output: 5
💡 Note: Split after index 0: left="0" (1 zero), right="11101" (4 ones), score = 1+4 = 5. This is the maximum possible.
Example 2 — All Zeros
$ Input: s = "00"
Output: 1
💡 Note: Only one valid split: left="0" (1 zero), right="0" (0 ones), score = 1+0 = 1.
Example 3 — Mixed String
$ Input: s = "1111"
Output: 3
💡 Note: Best split after index 0: left="1" (0 zeros), right="111" (3 ones), score = 0+3 = 3.

Constraints

  • 2 ≤ s.length ≤ 500
  • The string s consists of zeros and ones only

Visualization

Tap to expand
Maximum Score After Splitting a String INPUT String s = "011101" 0 i=0 1 i=1 1 i=2 1 i=3 0 i=4 1 i=5 Score Formula: zeros(left) + ones(right) Possible Splits: "0" | "11101" "01" | "1101" "011" | "101" "0111" | "01" "01110" | "1" Both parts must be non-empty ALGORITHM STEPS 1 Count Total Ones Total ones = 4 2 Initialize Counters zeros=0, ones=4, max=0 3 Iterate Each Split Update zeros/ones count 4 Track Maximum max = max(zeros + ones) Split Scores: i=0: "0"|"11101" = 1+4 = 5 MAX i=1: "01"|"1101" = 1+3 = 4 i=2: "011"|"101" = 1+2 = 3 i=3: "0111"|"01" = 1+1 = 2 i=4: "01110"|"1" = 2+1 = 3 FINAL RESULT Optimal Split at i=0 0 LEFT 1 zero 11101 RIGHT 4 ones Score Calculation 1 (zeros) + 4 (ones) = 5 OUTPUT 5 Maximum Score = 5 Key Insight: Instead of recounting for each split, use running counts: increment zeros when seeing '0', decrement ones when seeing '1'. This gives O(n) time complexity vs O(n^2) brute force. TutorialsPoint - Maximum Score After Splitting a String | Optimal Solution O(n)
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen