Maximum Subsequence Score — LeetCode 2542 Python Solution
- Problem
- #2542
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k.
Example
- Input
- nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
- Output
- 12
- Explanation
- The four possible subsequence scores are:
Python solution
class Solution:
def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
nums = sorted(zip(nums2, nums1), reverse=True)
q = []
ans = s = 0
for a, b in nums:
s += b
heappush(q, b)
if len(q) == k:
ans = max(ans, s * a)
s -= heappop(q)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2542. Maximum Subsequence Score is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 2542. Maximum Subsequence Score?
- LeetCode 2542. Maximum Subsequence Score is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2542. Maximum Subsequence Score?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2542. Maximum Subsequence Score?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2542. Maximum Subsequence Score cover?
- LeetCode 2542. Maximum Subsequence Score is tagged Greedy, Array, Sorting and Heap (Priority Queue) on LeetCode.