SDE & MLE Prep

2542. Maximum Subsequence Score

Problem

Choose k indices. Their score is (sum of nums1 at those indices) × (minimum of nums2 at those indices). Return the maximum possible score.

Example: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3 → 12 (indices 0, 2, 3: (1 + 3 + 2) × 2)

Constraints: n ≤ 10⁵.

Sort pairs by nums2 descending. When we reach pair i, nums2[i] is the minimum of everything seen so far — so fix it as the multiplier and pair it with the k largest nums1 among the seen pairs, kept in a size-k min-heap with a running sum.

Complexity: O(n log n).

class Solution:
    def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
        heap, total, best = [], 0, 0
        for b, a in sorted(zip(nums2, nums1), reverse=True):
            heappush(heap, a)
            total += a
            if len(heap) > k:
                total -= heappop(heap)
            if len(heap) == k:
                best = max(best, total * b)
        return best