Maximum Subsequence Score — LeetCode 2542 Python Solution

MediumGreedyArraySortingHeap (Priority Queue)
Problem
#2542
Reading time
3 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview