Maximum Subsequence Score Problem
Description
LeetCode Problem 2542.
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.
For chosen indices i_0, i_1, ..., i_(k - 1), your score is defined as:
- The sum of the selected elements from
nums1multiplied with the minimum of the selected elements fromnums2. - It can defined simply as:
(nums1[i_0] + nums1[i_1] +...+ nums1[i_(k - 1)]) * min(nums2[i_0] , nums2[i_1], ... ,nums2[i_(k - 1)]).
Return the maximum possible score.
A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.
Example 1:
Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
Output: 12
Explanation:
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
Example 2:
Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
Output: 30
Explanation:
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
Constraints:
n == nums1.length == nums2.length1 <= n <= 10^50 <= nums1[i], nums2[j] <= 10^51 <= k <= n
Solution
Approach: Sort + Min-Heap
The score is sum(chosen nums1) * min(chosen nums2). Fix the minimum of nums2: sort the pairs by nums2 in descending order and treat each pair in turn as the one with the smallest nums2 so far. Every pair seen earlier has a nums2 at least as large, so any of them may be chosen.
For that fixed minimum we want the k largest nums1 values among the pairs seen so far, including the current one. Keep them in a min-heap with their running sum s: push the current nums1, and once the heap holds k values, record s * nums2 and pop the smallest value so the heap is ready for the next pair.
Complexity: O(n log n) time for sorting and the heap, and O(n) extra space.
from heapq import heappush, heappop
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