All Divisions With the Highest Score of a Binary Array - Problem
Imagine you're a strategic analyst tasked with finding the optimal division points in a binary array to maximize your scoring potential!
Given a binary array nums of length n, you can divide it at any index i (where 0 โค i โค n) into two parts:
- Left part: Elements from index
0toi-1 - Right part: Elements from index
iton-1
Your division score is calculated as:
Score = (Number of 0's in left part) + (Number of 1's in right part)
Your mission is to find all indices that produce the highest possible division score. The strategy is to reward having more 0's on the left and more 1's on the right!
Special cases:
- If
i = 0: Left part is empty, right part contains all elements - If
i = n: Left part contains all elements, right part is empty
Input & Output
example_1.py โ Basic Case
$
Input:
[0,0,1,0]
โบ
Output:
[2,4]
๐ก Note:
Division at i=2: Left=[0,0] has 2 zeros, Right=[1,0] has 1 one โ Score=3. Division at i=4: Left=[0,0,1,0] has 3 zeros, Right=[] has 0 ones โ Score=3. Both achieve maximum score of 3.
example_2.py โ All Ones
$
Input:
[1,1,1]
โบ
Output:
[0]
๐ก Note:
Division at i=0: Left=[] has 0 zeros, Right=[1,1,1] has 3 ones โ Score=3. Any other division reduces the number of ones on right without gaining zeros on left, so i=0 is optimal.
example_3.py โ All Zeros
$
Input:
[0,0,0]
โบ
Output:
[3]
๐ก Note:
Division at i=3: Left=[0,0,0] has 3 zeros, Right=[] has 0 ones โ Score=3. This maximizes zeros on left since there are no ones to put on right.
Visualization
Tap to expand
Understanding the Visualization
1
Setup the Array
Place binary array elements and consider all possible division points
2
Calculate Initial Score
Start at division point 0 with score = total ones (all on right)
3
Move Division Point
As we move right, update score based on element type we're moving
4
Track Maximum
Keep track of all division points that achieve maximum score
Key Takeaway
๐ฏ Key Insight: The optimal solution leverages the fact that moving the division point by one position only changes the score by ยฑ1, enabling efficient O(n) incremental calculation.
Time & Space Complexity
Time Complexity
O(n)
Single pass to count initial ones, then one pass to check all division points
โ Linear Growth
Space Complexity
O(1)
Only using variables for tracking score and maximum, plus result array
โ Linear Space
Constraints
- 1 โค nums.length โค 105
- nums[i] is either 0 or 1
- Division point i can range from 0 to n (inclusive)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code