#2542
Maximum Subsequence Score
MediumArrayGreedySortingHeap (Priority Queue)GreedySortingHeap (Priority Queue)
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)
The optimal solution leverages sorting and a min-heap to efficiently find the maximum score. By sorting based on nums2, we can ensure that we always consider the largest possible minimum value while maintaining the sum of the largest k elements from nums1.
⚙️
Algorithm
4 steps- 1Step 1: Pair elements of nums1 and nums2 and sort them based on nums2 in descending order.
- 2Step 2: Use a min-heap to keep track of the largest k elements from nums1 as we iterate through the sorted pairs.
- 3Step 3: Calculate the score using the sum of elements in the heap multiplied by the current nums2 value (which is the minimum for the current k elements).
- 4Step 4: Update the maximum score encountered during the iteration.
solution.py18 lines
1# Full working Python code
2import heapq
3
4def maxSubsequenceScore(nums1, nums2, k):
5 paired = sorted(zip(nums1, nums2), key=lambda x: -x[1])
6 max_score = 0
7 sum_nums1 = 0
8 min_heap = []
9
10 for num1, num2 in paired:
11 heapq.heappush(min_heap, num1)
12 sum_nums1 += num1
13 if len(min_heap) > k:
14 sum_nums1 -= heapq.heappop(min_heap)
15 if len(min_heap) == k:
16 max_score = max(max_score, sum_nums1 * num2)
17
18 return max_scoreℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the paired elements and the min-heap.
- 1Choosing the right indices is crucial for maximizing the score.
- 2Sorting based on the second array allows us to efficiently manage the minimum value.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.