2542. Maximum Subsequence Score
Problem
Choose k indices. Their score is (sum of nums1 at those indices) × (minimum of nums2 at those indices). Return the maximum possible score.
Example: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3 → 12 (indices 0, 2, 3: (1 + 3 + 2) × 2)
Constraints: n ≤ 10⁵.
Sort pairs by nums2 descending. When we reach pair i, nums2[i] is the minimum of everything seen so far — so fix it as the multiplier and pair it with the k largest nums1 among the seen pairs, kept in a size-k min-heap with a running sum.
Complexity: O(n log n).
class Solution:
def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
heap, total, best = [], 0, 0
for b, a in sorted(zip(nums2, nums1), reverse=True):
heappush(heap, a)
total += a
if len(heap) > k:
total -= heappop(heap)
if len(heap) == k:
best = max(best, total * b)
return best
assert Solution().maxScore([1, 3, 3, 2], [2, 1, 3, 4], 3) == 12
assert Solution().maxScore([4, 2, 3, 1, 1], [7, 5, 10, 9, 6], 1) == 30
assert Solution().maxScore([2, 1, 14, 12], [11, 7, 13, 6], 3) == 168
class Solution {
public long maxScore(int[] nums1, int[] nums2, int k) {
int n = nums1.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, (x, y) -> nums2[y] - nums2[x]);
PriorityQueue<Integer> heap = new PriorityQueue<>();
long total = 0, best = 0;
for (int i : idx) {
heap.add(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;
}
}
type IntHeap []int // min-heap
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func maxScore(nums1 []int, nums2 []int, k int) int64 {
idx := make([]int, len(nums1))
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(a, b int) bool { return nums2[idx[a]] > nums2[idx[b]] }) // by nums2 desc
h, total, best := &IntHeap{}, 0, 0
for _, i := range idx { // nums2[i] is the minimum of the chosen set so far
heap.Push(h, nums1[i])
total += nums1[i]
if h.Len() > k { // keep the k largest nums1 values
total -= heap.Pop(h).(int)
}
if h.Len() == k {
best = max(best, total*nums2[i])
}
}
return int64(best)
}