InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Heap & Priority Queue

Maximum Subsequence Score

medium Original ↗ 00:00

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 Indices {2, 3} give sum 14 + 12 = 26, min min(5, 5) = 5, score 130. Other pairs score lower: {0, 3} gives sum 14, min 5, score 70; {0, 1} gives sum 3, min 7, score 21.

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug