#2155
All Divisions With the Highest Score of a Binary Array
MediumArrayHash MapArray
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 leverages prefix sums to efficiently calculate the number of zeros and ones without redundant counting. This reduces the time complexity significantly.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the total number of ones in the entire array.
- 2Step 2: Initialize counters for left zeros and a list for indices with the maximum score.
- 3Step 3: Loop through the array, updating the count of left zeros and calculating the right ones using the total count minus the left count.
- 4Step 4: For each index, compute the score and update the maximum score and the list of indices accordingly.
- 5Step 5: Return the list of indices that have the highest score.
solution.py19 lines
1# Full working Python code
2
3def maxDivScore(nums):
4 total_ones = sum(nums)
5 left_zeros = 0
6 max_score = -1
7 indices = []
8 for i in range(len(nums) + 1):
9 right_ones = total_ones - (sum(nums[:i]))
10 score = left_zeros + right_ones
11 if score > max_score:
12 max_score = score
13 indices = [i]
14 elif score == max_score:
15 indices.append(i)
16 if i < len(nums) and nums[i] == 0:
17 left_zeros += 1
18 return indices
19ℹ
Complexity note: This complexity is achieved by calculating the total number of ones in a single pass and then using a single loop to calculate scores, avoiding redundant counting.
- 1Understanding how to efficiently count elements in subarrays is crucial.
- 2Using prefix sums can drastically reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.