Maximum Subsequence Score
Explanation & Solution
Description
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 of length k from nums1 and nums2.
The score of the chosen subsequence is defined as the sum of the selected elements from nums1 multiplied by the minimum of the selected elements from nums2.
Return the maximum possible score.
A subsequence of indices is a set of distinct indices chosen from [0, 1, ..., n - 1]. The elements selected by those indices from nums1 and nums2 are used to compute the score.
Examples
Output: 12
Explanation: Selecting indices 0, 2, and 3 gives nums1 values [1,3,2] (sum = 6) and nums2 values [2,3,4] (min = 2). Score = 6 * 2 = 12.
Output: 30
Explanation: Selecting index 2 gives nums1 value [3] (sum = 3) and nums2 value [10] (min = 10). Score = 3 * 10 = 30.
Output: 168
Explanation: Selecting indices 0, 2, and 3 gives nums1 values [2,14,12] (sum = 28) and nums2 values [11,13,6] (min = 6). Score = 28 * 6 = 168.
Constraints
n == nums1.length == nums2.length1 <= n <= 10^50 <= nums1[i], nums2[i] <= 10^51 <= k <= n
Approach
Top K Elements pattern
1. Sort Indices by nums2 in Descending Order
- Create an array of indices
[0, 1, ..., n-1]and sort them by their correspondingnums2values in descending order. - This ensures that as we iterate, the current
nums2[idx]is always the minimum among allnums2values considered so far.
2. Initialize a Min-Heap and Running Sum
- Use a min-heap of size at most
kto track the largestkvalues fromnums1seen so far. - Maintain a running
heapSumto efficiently compute the sum of elements in the heap.
3. Iterate Through Sorted Indices
- For each index (in sorted order by
nums2descending): - Push
nums1[idx]into the heap and add it toheapSum. - If the heap size exceeds
k, pop the smallest element and subtract it fromheapSum. This ensures we always keep the top-k largestnums1values.
4. Compute Score When Heap Has Exactly k Elements
- When the heap size equals
k, compute the score asheapSum * nums2[idx]. - Since indices are sorted by
nums2descending,nums2[idx]is guaranteed to be the minimum of all selectednums2values. - Track the maximum score across all iterations.
5. Return the Maximum Score
- After processing all indices, return the maximum score found.
Key Insight
By sorting indices by nums2 descending and iterating in that order, the current nums2 value is always the minimum for any subset of indices considered so far. The min-heap greedily maintains the top-k nums1 values to maximize the sum component. This transforms a combinatorial problem into a single-pass greedy algorithm.
Visualization
No animation available