All Divisions With the Highest Score of a Binary Array Problem
Description
LeetCode Problem 2155.
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) nums_left and nums_right:
nums_lefthas all the elements ofnumsbetween index0andi - 1(inclusive), whilenums_righthas all the elements of nums between indexiandn - 1(inclusive).- If
i == 0,nums_leftis empty, whilenums_righthas all the elements ofnums. - If
i == n,nums_lefthas all the elements of nums, whilenums_rightis empty.
The division score of an index i is the sum of the number of 0's in nums_left and the number of 1's in nums_right.
Return all distinct indices that have the highest possible division score. You may return the answer in any order.
Example 1:
Input: nums = [0,0,1,0]
Output: [2,4]
Explanation: Division at index
- 0: nums_left is []. nums_right is [0,0,1,0]. The score is 0 + 1 = 1.
- 1: nums_left is [0]. nums_right is [0,1,0]. The score is 1 + 1 = 2.
- 2: nums_left is [0,0]. nums_right is [1,0]. The score is 2 + 1 = 3.
- 3: nums_left is [0,0,1]. nums_right is [0]. The score is 2 + 0 = 2.
- 4: nums_left is [0,0,1,0]. nums_right is []. The score is 3 + 0 = 3.
Indices 2 and 4 both have the highest possible division score 3.
Note the answer [4,2] would also be accepted.
Example 2:
Input: nums = [0,0,0]
Output: [3]
Explanation: Division at index
- 0: nums_left is []. nums_right is [0,0,0]. The score is 0 + 0 = 0.
- 1: nums_left is [0]. nums_right is [0,0]. The score is 1 + 0 = 1.
- 2: nums_left is [0,0]. nums_right is [0]. The score is 2 + 0 = 2.
- 3: nums_left is [0,0,0]. nums_right is []. The score is 3 + 0 = 3.
Only index 3 has the highest possible division score 3.
Example 3:
Input: nums = [1,1]
Output: [0]
Explanation: Division at index
- 0: nums_left is []. nums_right is [1,1]. The score is 0 + 2 = 2.
- 1: nums_left is [1]. nums_right is [1]. The score is 0 + 1 = 1.
- 2: nums_left is [1,1]. nums_right is []. The score is 0 + 0 = 0.
Only index 0 has the highest possible division score 2.
Constraints:
n == nums.length1 <= n <= 10^5nums[i]is either0or1.
Solution
Approach: Prefix Sum
Splitting at index i scores the number of 0s on the left plus the number of 1s on the right. Keep l0, the zeros seen so far (starting at 0), and r1, the ones still to the right (starting at the total number of ones).
For i = 0 the score is r1. Then for each i from 1 to n, update l0 and r1 with nums[i - 1] and compute t = l0 + r1. If t equals the best score mx, add i to the answer. If t is larger, set mx = t and restart the answer with just i.
Complexity: O(n) time and O(1) extra space (excluding the answer).
class Solution:
def maxScoreIndices(self, nums: List[int]) -> List[int]:
l0, r1 = 0, sum(nums)
mx = r1
ans = [0]
for i, x in enumerate(nums, 1):
l0 += x ^ 1
r1 -= x
t = l0 + r1
if mx == t:
ans.append(i)
elif mx < t:
mx = t
ans = [i]
return ans