Problem Description
Given a binary array nums, we want to find all indices i (from 0 to n, inclusive) where dividing the array into nums_left = nums[0...i-1] and nums_right = nums[i...n-1] results in the highest possible division score. The division score is defined as the number of 0's in nums_left plus the number of 1's in nums_right.
Key Insights
- Use a single pass to calculate total ones in the array (which gives the initial count for the right side when i = 0).
- As you iterate from i = 0 to n, maintain a running count of zeros in the left part.
- For each index, compute the score as current count of left zeros plus current count of right ones.
- When moving the split, update the counts accordingly: if the current element is 0, it contributes to left zeros; if it is 1, it is removed from the right side.
- Track the maximum score seen and record indices matching that score.
Space and Time Complexity
Time Complexity: O(n) – we make one pass through the array. Space Complexity: O(1) – only a few counters and variables are used (excluding the output list).
Solution
The solution uses a greedy one-pass approach. First, count the total number of ones in the input array, which represents the count of ones in the right partition when the split is at index 0. Then iterate through the array considering each possible division index. For each index, compute the score by adding the accumulated left zeros and the current right ones count. If the current element is 0, increment the left zero count; if it is 1, decrement the right ones count (since it moves from the right to the left after the split). Track the maximum score observed and store the indices that achieve this maximum.