MediumNo. 2542

Maximum Subsequence Score — LeetCode 2542 Python Solution

Topics
Greedy, Array, Sorting, Heap (Priority Queue)
On a study list
LeetCode 75
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

PythonSolution
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

Time
O(n × log n)
Space · auxiliary
O(n)

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

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.