#3781
Maximum Score After Binary Swaps
MediumArrayStringGreedyHeap (Priority Queue)GreedyHeap
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can maximize the score by moving '1's leftwards to cover the highest values in nums. This can be done in a single pass using a greedy approach.
⚙️
Algorithm
3 steps- 1Step 1: Initialize score and a priority queue to store values of nums at '1' positions.
- 2Step 2: Traverse the string s, adding nums[i] to the score for '1's and pushing nums[i] to the queue for '0's before '1's.
- 3Step 3: Pop from the queue to maximize the score as we encounter '1's.
solution.py13 lines
1import heapq
2
3def maxScore(nums, s):
4 score = 0
5 max_heap = []
6 for i in range(len(s)):
7 if s[i] == '1':
8 score += nums[i]
9 if max_heap:
10 score += -heapq.heappop(max_heap)
11 else:
12 heapq.heappush(max_heap, -nums[i])
13 return scoreℹ
Complexity note: Using a priority queue allows us to efficiently manage the values we can swap, leading to a linearithmic time complexity.
- 1Swapping '1's left maximizes score.
- 2Using a priority queue helps efficiently manage potential swaps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.