Maximum Subsequence Score
Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #2542
Pick k indices. The score is (sum of nums1 at those indices) × (min of nums2 at those indices). Return the maximum possible score.
Examples
text
nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3 → 12 (indices 0,2,3: (1+3+2) × min(2,3,4) = 6 × 2)
nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1 → 30 (index 2: 3 × 10)Hints
- Fix which element supplies the minimum of nums2. Then you want the largest k−1 nums1 values among elements with a nums2 at least that big.
- Sort the pairs by nums2 descending. As you sweep, every earlier element has a larger or equal nums2.
Approach
Sort the pairs (nums2[i], nums1[i]) by nums2 descending. Sweep, keeping a min-heap of the k largest nums1 values seen so far and their running sum:
text
for (b, a) in sorted pairs:
push a; sum += a
if heap size > k: sum -= pop() # drop the smallest nums1
if heap size == k: best = max(best, sum * b)When we're at pair (b, a), b is the smallest nums2 so far, so it is the min of any selection made from the prefix. Does the selection have to include a itself? No. If a was just popped, the remaining k elements all have nums2 ≥ b, so their true score is ≥ sum*b. We never overestimate, and the optimum is reached at its own min element. O(n log n).
Complexity
Time: O(n log n). Space: O(n).
Python solution
import heapq
def maxScore(nums1, nums2, k):
pairs = sorted(zip(nums2, nums1), reverse=True)
heap, s, best = [], 0, 0
for b, a in pairs:
heapq.heappush(heap, a)
s += a
if len(heap) > k:
s -= heapq.heappop(heap)
if len(heap) == k:
best = max(best, s * b)
return bestJavaScript solution
function maxScore(nums1, nums2, k) {
const idx = [...nums1.keys()].sort((i, j) => nums2[j] - nums2[i]);
const heap = [];
const push = (x) => { heap.push(x); let i = heap.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (heap[p] <= heap[i]) break; [heap[i], heap[p]] = [heap[p], heap[i]]; i = p; } };
const pop = () => { const top = heap[0], last = heap.pop(); if (heap.length) { heap[0] = last; let i = 0; for (;;) { const l = 2 * i + 1, r = l + 1; let m = i; if (l < heap.length && heap[l] < heap[m]) m = l; if (r < heap.length && heap[r] < heap[m]) m = r; if (m === i) break; [heap[i], heap[m]] = [heap[m], heap[i]]; i = m; } } return top; };
let s = 0, best = 0;
for (const i of idx) {
push(nums1[i]); s += nums1[i];
if (heap.length > k) s -= pop();
if (heap.length === k) best = Math.max(best, s * nums2[i]);
}
return best;
}