#1422
Maximum Score After Splitting a String
EasyStringPrefix SumPrefix SumTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single pass to calculate the score efficiently. We maintain a count of zeros in the left substring and derive the count of ones in the right substring using the total count of ones.
⚙️
Algorithm
4 steps- 1Step 1: Count the total number of ones in the string.
- 2Step 2: Initialize a variable to keep track of the number of zeros in the left substring and the maximum score.
- 3Step 3: Iterate through the string up to the second last character, updating the count of zeros and calculating the score using the total ones minus the ones in the left substring.
- 4Step 4: Update the maximum score accordingly.
solution.py12 lines
1# Full working Python code
2
3def maxScore(s):
4 total_ones = s.count('1')
5 left_zeros = 0
6 max_score = 0
7 for i in range(len(s) - 1):
8 if s[i] == '0':
9 left_zeros += 1
10 score = left_zeros + (total_ones - (s[:i + 1].count('1')))
11 max_score = max(max_score, score)
12 return max_scoreℹ
Complexity note: This complexity is linear because we only traverse the string a constant number of times, making it efficient.
- 1The score is maximized by balancing zeros on the left and ones on the right.
- 2Precomputing the total number of ones allows for efficient score calculation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.