Browse curriculum

Maximum Subsequence Score (LeetCode 2542)

Maximum Subsequence Score (LeetCode 2542): pick k indices to maximise sum(nums1) × min(nums2). Sort the pairs by nums2, largest first, and keep the k largest nums1 seen so far in a min-heap; each pair in turn plays the minimum.

Problem Understanding

Maximum Subsequence Score (LeetCode 2542): given two arrays nums1 and nums2 of length n and an integer k, choose k indices. The score is the sum of the chosen nums1 values times the minimum of the chosen nums2 values. Return the maximum possible score.

Examples: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3 → 12 (indices 0, 2, 3: (1 + 3 + 2) × 2); nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1 → 30.

The Intuition: Fix the Minimum, Maximise the Sum

Two things fight each other: big nums1 values and a big minimum nums2. Fix one of them by trying each pair as the minimum.

  1. Sort the pairs by nums2, largest first. At pair i, every pair before it has a larger or equal nums2, so nums2[i] is the minimum of any choice that includes pair i and earlier pairs.
  2. Keep the k largest nums1 so far in a min-heap, with their running sum. Push each value; if the heap grows past k, pop the smallest.
  3. When the heap holds k values, score = sum × nums2[i]. Keep the best.

The size-k min-heap is the same tool as in Kth Largest Element in an Array: it holds the k largest values seen, with the smallest of them on top, ready to be dropped.

Maximum Subsequence Score Visualization

OUTLINED = IN THE HEAP · GREEN = THE nums2 THE SCORE USES

SORT BY nums2, LARGEST FIRST

nums2, sorted largest first

4
3
2
1

nums1 of the same pair (original index below)

2

3

3

2

1

0

3

1

min-heap of nums1 · at most k = 3

sum

0

score

:

best

0

 

Sort the pairs by nums2, largest first: (2, 4) (3, 3) (1, 2) (3, 1)

Next

Pair (2, 4): push 2, sum = 2

Free preview: the first 3 of 9 steps

nums1

nums2

k

3

The two rows are the pairs after sorting by nums2. Columns whose nums1 is in the heap are outlined, and when the heap holds k values the current nums2 turns green: it is the minimum the score uses. The heap array is underneath. Try Big nums1, small nums2, where the largest nums1 is a trap.

Maximum Subsequence Score Dry Run

Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3. Sorted by nums2, largest first: (2, 4), (3, 3), (1, 2), (3, 1).

Pair (nums1, nums2) Heap holds sum Score best
(2, 4) 2 2 (fewer than k) 0
(3, 3) 2, 3 5 (fewer than k) 0
(1, 2) 1, 2, 3 6 6 × 2 = 12 12
(3, 1) push 3, pop 1: 2, 3, 3 8 8 × 1 = 8 12

Answer: 12.

Maximum Subsequence Score LeetCode Solution

Sort indices by nums2 descending, then a size-k min-heap and a running sum. JavaScript and TypeScript bring a small MinHeap; C sorts with qsort and keeps its own array heap. Scores need 64-bit integers.

Maximum Subsequence Score Code
1class MinHeap {
2 constructor(less = (a, b) => a < b) {
3 this.items = [];
4 this.less = less;
5 }
6
7 size() {
8 return this.items.length;
9 }
10
11 peek() {
12 return this.items[0];
13 }
14
15 push(x) {
16 const a = this.items;
17 a.push(x);
18 let i = a.length - 1;
19 while (i > 0 && this.less(a[i], a[(i - 1) >> 1])) {
20 const p = (i - 1) >> 1;
21 [a[i], a[p]] = [a[p], a[i]];
22 i = p;
23 }
24 }
25
26 pop() {
27 const a = this.items;
28 const top = a[0];
29 const last = a.pop();
30 if (a.length > 0) {
31 a[0] = last;
32 let i = 0;
33 while (true) {
34 const l = 2 * i + 1, r = l + 1;
35 let m = i;
36 if (l < a.length && this.less(a[l], a[m])) m = l;
37 if (r < a.length && this.less(a[r], a[m])) m = r;
38 if (m === i) break;
39 [a[i], a[m]] = [a[m], a[i]];
40 i = m;
41 }
42 }
43 return top;
44 }
45}
46
47var maxScore = function(nums1, nums2, k) {
48 const order = nums1.map((_, i) => i).sort((x, y) => nums2[y] - nums2[x]);
49 const heap = new MinHeap();
50 let total = 0, best = 0;
51 for (const i of order) {
52 heap.push(nums1[i]);
53 total += nums1[i];
54 if (heap.size() > k) {
55 total -= heap.pop();
56 }
57 if (heap.size() === k) {
58 best = Math.max(best, total * nums2[i]);
59 }
60 }
61 return best;
62};

Maximum Subsequence Score in Python, Java, C++, TypeScript and C

Maximum Subsequence Score in Python
class Solution:
    def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
        pairs = sorted(zip(nums1, nums2), key=lambda p: -p[1])
        heap = []
        total = best = 0
        for a, b in pairs:
            heapq.heappush(heap, a)
            total += a
            if len(heap) > k:
                total -= heapq.heappop(heap)
            if len(heap) == k:
                best = max(best, total * b)
        return best
Maximum Subsequence Score in Java
class Solution {
    public long maxScore(int[] nums1, int[] nums2, int k) {
        int n = nums1.length;
        Integer[] order = new Integer[n];
        for (int i = 0; i < n; i++) {
            order[i] = i;
        }
        Arrays.sort(order, (x, y) -> nums2[y] - nums2[x]);
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        long total = 0, best = 0;
        for (int i : order) {
            heap.offer(nums1[i]);
            total += nums1[i];
            if (heap.size() > k) {
                total -= heap.poll();
            }
            if (heap.size() == k) {
                best = Math.max(best, total * nums2[i]);
            }
        }
        return best;
    }
}
Maximum Subsequence Score in C++
class Solution {
public:
    long long maxScore(vector<int>& nums1, vector<int>& nums2, int k) {
        int n = nums1.size();
        vector<int> order(n);
        iota(order.begin(), order.end(), 0);
        sort(order.begin(), order.end(), [&](int x, int y) { return nums2[x] > nums2[y]; });
        priority_queue<int, vector<int>, greater<int>> heap;
        long long total = 0, best = 0;
        for (int i : order) {
            heap.push(nums1[i]);
            total += nums1[i];
            if ((int)heap.size() > k) {
                total -= heap.top();
                heap.pop();
            }
            if ((int)heap.size() == k) {
                best = max(best, total * nums2[i]);
            }
        }
        return best;
    }
};
Maximum Subsequence Score in TypeScript
class MinHeap<T> {
    private items: T[] = [];

    constructor(private less: (a: T, b: T) => boolean = (a, b) => a < b) {}

    size(): number {
        return this.items.length;
    }

    peek(): T {
        return this.items[0];
    }

    push(x: T): void {
        const a = this.items;
        a.push(x);
        let i = a.length - 1;
        while (i > 0 && this.less(a[i], a[(i - 1) >> 1])) {
            const p = (i - 1) >> 1;
            [a[i], a[p]] = [a[p], a[i]];
            i = p;
        }
    }

    pop(): T {
        const a = this.items;
        const top = a[0];
        const last = a.pop()!;
        if (a.length > 0) {
            a[0] = last;
            let i = 0;
            while (true) {
                const l = 2 * i + 1, r = l + 1;
                let m = i;
                if (l < a.length && this.less(a[l], a[m])) m = l;
                if (r < a.length && this.less(a[r], a[m])) m = r;
                if (m === i) break;
                [a[i], a[m]] = [a[m], a[i]];
                i = m;
            }
        }
        return top;
    }
}

function maxScore(nums1: number[], nums2: number[], k: number): number {
    const order = nums1.map((_, i) => i).sort((x, y) => nums2[y] - nums2[x]);
    const heap = new MinHeap<number>();
    let total = 0, best = 0;
    for (const i of order) {
        heap.push(nums1[i]);
        total += nums1[i];
        if (heap.size() > k) {
            total -= heap.pop();
        }
        if (heap.size() === k) {
            best = Math.max(best, total * nums2[i]);
        }
    }
    return best;
}
Maximum Subsequence Score in C
static int* byValue;

static int nums2Desc(const void* x, const void* y) {
    return byValue[*(const int*)y] - byValue[*(const int*)x];
}

static void push(int* h, int* size, int v) {
    int i = (*size)++;
    h[i] = v;
    while (i > 0 && h[(i - 1) / 2] > h[i]) {
        int p = (i - 1) / 2, t = h[p];
        h[p] = h[i];
        h[i] = t;
        i = p;
    }
}

static int pop(int* h, int* size) {
    int top = h[0], i = 0;
    h[0] = h[--(*size)];
    for (;;) {
        int m = i, l = 2 * i + 1, r = l + 1;
        if (l < *size && h[l] < h[m]) m = l;
        if (r < *size && h[r] < h[m]) m = r;
        if (m == i) return top;
        int t = h[m];
        h[m] = h[i];
        h[i] = t;
        i = m;
    }
}

long long maxScore(int* nums1, int nums1Size, int* nums2, int nums2Size, int k) {
    int* order = malloc(nums1Size * sizeof(int));
    for (int i = 0; i < nums1Size; i++) {
        order[i] = i;
    }
    byValue = nums2;
    qsort(order, nums1Size, sizeof(int), nums2Desc);
    int* heap = malloc((k + 1) * sizeof(int));
    int size = 0;
    long long total = 0, best = 0;
    for (int t = 0; t < nums1Size; t++) {
        int i = order[t];
        push(heap, &size, nums1[i]);
        total += nums1[i];
        if (size > k) {
            total -= pop(heap, &size);
        }
        if (size == k && total * nums2[i] > best) {
            best = total * nums2[i];
        }
    }
    free(order);
    free(heap);
    return best;
}

Edge Cases & Common Mistakes

  • Sorting by nums1 instead: the minimum nums2 is then unknown at each step.
  • Scoring before the heap holds k values: a choice must have exactly k indices.
  • Overflow: a sum of up to 10⁵ values of 10⁵ times another 10⁵ needs 64-bit integers.
  • k = 1: the answer is the best single nums1[i] × nums2[i]; the heap holds one value at a time.
  • k = n: every index is chosen, so the score is sum(nums1) × min(nums2).

Summary

Sort the pairs by nums2 descending. A min-heap keeps the k largest nums1 seen and their sum; each time it holds k values, score = sum × current nums2. Return the best. O(n log n) time, O(n) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Sort the pairs

    Sort (nums1[i], nums2[i]) by nums2, largest first.

  2. Keep the k largest nums1

    Push each nums1 onto a min-heap and add it to a running sum; if the heap holds more than k, pop the smallest and subtract it.

  3. Score

    Whenever the heap holds exactly k, the score is sum × current nums2; keep the best.

Frequently asked questions

Why sort by nums2 from largest to smallest?

The score depends on the smallest nums2 among the chosen indices. Walking the pairs in decreasing nums2 means that when pair i is reached, every earlier pair has nums2 at least as large, so if pair i is chosen, nums2[i] is the minimum. That fixes one factor of the score and leaves only the sum to maximise.


Why a min-heap of nums1?

With the minimum fixed, the best sum comes from the k largest nums1 among the pairs seen so far. A min-heap of size k keeps exactly those: push each new value, and when the heap has k + 1 values, pop the smallest. The running sum is updated with each push and pop.


What if the heap pops the current pair’s own nums1?

Then the score computed at that step uses nums2[i] with k values that do not include pair i. All k of them have nums2 at least nums2[i], so their real score is at least as large and was counted when the last of them was added. The extra score is never higher than a real one, so the answer is not affected.


Why not try every subset?

There are C(n, k) subsets, which is far too many for n up to 100,000. Sorting plus a heap visits each pair once with O(log k) heap work.

New to the technique behind this problem? Watch it run step by step:

Heaps Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description