All Divisions With the Highest Score of a Binary Array - Problem

You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 ≤ i ≤ n) into two arrays (possibly empty) numsleft and numsright:

numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive).

If i == 0, numsleft is empty, while numsright has all the elements of nums.

If i == n, numsleft has all the elements of nums, while numsright is empty.

The division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright.

Return all distinct indices that have the highest possible division score. You may return the answer in any order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,0,1,1,1]
Output: [2]
💡 Note: Division at index 2: left=[0,0] has 2 zeros, right=[1,1,1] has 3 ones, score=2+3=5 (maximum)
Example 2 — Multiple Answers
$ Input: nums = [0,0,0]
Output: [3]
💡 Note: Division at index 3: left=[0,0,0] has 3 zeros, right=[] has 0 ones, score=3+0=3 (maximum)
Example 3 — All Ones
$ Input: nums = [1,1]
Output: [0]
💡 Note: Division at index 0: left=[] has 0 zeros, right=[1,1] has 2 ones, score=0+2=2 (maximum)

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Visualization

Tap to expand
All Divisions With Highest Score INPUT Binary Array nums: 0 i=0 0 i=1 1 i=2 1 i=3 1 i=4 Division at index i splits into: nums_left nums_right Division Score = 0s in left + 1s in right n = 5 Total 0s: 2, Total 1s: 3 ALGORITHM STEPS 1 Count total 1s ones_right = 3 2 Init zeros_left = 0 Track 0s as we go 3 Scan and compute Score at each division i 0s_L 1s_R Score 0 0 3 3 1 1 3 4 2 2 3 5 MAX 3 2 2 4 4 2 1 3 5 2 0 2 4 Find max indices Max score = 5 at i=2 FINAL RESULT Optimal Division at i = 2 nums_left [0, 0] nums_right [1, 1, 1] Score Calculation 0s in left: 2 1s in right: 3 Max Score = 5 Output Array: [2] Index 2 has highest score Key Insight: Instead of recalculating for each division, use prefix counting. Start with all 1s on right. As you move division point right: if element is 0, increment zeros_left; if 1, decrement ones_right. Time: O(n), Space: O(1) -- single pass to count, single pass to find max score indices. TutorialsPoint - All Divisions With the Highest Score of a Binary Array | Optimal Solution
Asked in
Google 45 Amazon 35 Microsoft 30 Apple 25
38.4K Views
Medium Frequency
~15 min Avg. Time
865 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