InterviewPrepKit

Home / Coding / Heap & Priority Queue

Maximum Subsequence Score

medium Original β†—
Solving tips
  • Key insight: the score mixes an additive sum with a min bottleneck, so fix the bottleneck by sorting pairs by nums2 descending.
  • Sweep in that order treating the current nums2 as the minimum multiplier; keep the k largest nums1 among elements seen in a size-k min-heap with a running sum.
  • Only record running_sum Γ— current_nums2 when the heap holds exactly k items, and always subtract popped values from the sum.
  • Target O(n log n) time and O(n) space; seed best = 0 since values can be 0, and sort by nums2 (not nums1).

Problem

You are given two integer arrays nums1 and nums2, both of length n, and a positive integer k.

You must choose a subsequence of exactly k indices i_1, i_2, ..., i_k (the indices, not the values, must be distinct). For a chosen set of indices, the score is defined as:

(sum of the selected nums1 values) Γ— (minimum of the selected nums2 values)

That is, add up the nums1 entries at your chosen indices, then multiply that sum by the smallest nums2 entry among those same indices.

Return the maximum possible score over all valid choices of k indices.

Examples

  • Input: nums1 = [1, 3, 3, 2], nums2 = [2, 1, 3, 4], k = 3 β†’ Output: 12 Pick indices {0, 2, 3}. nums1 sum = 1 + 3 + 2 = 6; nums2 min = min(2, 3, 4) = 2; score = 6 Γ— 2 = 12. No other triple beats it.
  • Input: nums1 = [4, 2, 3, 1, 1], nums2 = [7, 5, 10, 9, 6], k = 1 β†’ Output: 30 With k = 1, score is just nums1[i] Γ— nums2[i]. Index 2 gives 3 Γ— 10 = 30, the best single pick.
  • Input: nums1 = [2, 1, 14, 12], nums2 = [11, 7, 5, 5], k = 2 β†’ Output: 130 Pick indices {0, 3}: sum 2 + 12 = 14, min min(11, 5) = 5, score 70. Pick {0, 1}: sum 3, min 7, score 21. Best is {2, 3}? sum 26, min 5 = 130. Answer 130.

Constraints

  • n == nums1.length == nums2.length, with 1 <= n <= 10^5.
  • 0 <= nums1[i], nums2[j] <= 10^5.
  • 1 <= k <= n.

The 10^5 size rules out anything close to trying all C(n, k) subsets β€” you need roughly O(n log n).

Think about it first

Hint 1 The score couples two things that pull against each other: you want a large nums1 sum, but the multiplier is the *minimum* nums2 in the chosen set. What if you fixed which element is that minimum?
Hint 2 Sort the index pairs by their `nums2` value in **descending** order. If you scan in that order and treat the current element as the minimum multiplier, then everything you've already seen has a `nums2` value at least as large β€” so any of them is a legal partner.
Hint 3 For a fixed minimum, you want the `k` largest `nums1` values among the eligible elements. Maintain a **min-heap** of size `k` over the nums1 values plus a running sum; each new element becomes a candidate minimum, and `running_sum Γ— current_nums2` is a candidate answer.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.