|
| 1 | +/** |
| 2 | + * 2542. Maximum Subsequence Score |
| 3 | + * https://leetcode.com/problems/maximum-subsequence-score/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive |
| 7 | + * integer k. You must choose a subsequence of indices from nums1 of length k. |
| 8 | + * |
| 9 | + * For chosen indices i0, i1, ..., ik - 1, your score is defined as: |
| 10 | + * - The sum of the selected elements from nums1 multiplied with the minimum of the selected |
| 11 | + * elements from nums2. |
| 12 | + * - It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0], |
| 13 | + * nums2[i1], ... ,nums2[ik - 1]). |
| 14 | + * |
| 15 | + * Return the maximum possible score. |
| 16 | + * |
| 17 | + * A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} |
| 18 | + * by deleting some or no elements. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} nums1 |
| 23 | + * @param {number[]} nums2 |
| 24 | + * @param {number} k |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var maxScore = function(nums1, nums2, k) { |
| 28 | + const zipped = nums1.map((num1, i) => [num1, nums2[i]]).sort((a, b) => b[1] - a[1]); |
| 29 | + const heap = new MinPriorityQueue(); |
| 30 | + let result = 0; |
| 31 | + let sum = 0; |
| 32 | + |
| 33 | + for (const [num, min] of zipped) { |
| 34 | + heap.enqueue(num); |
| 35 | + sum += num; |
| 36 | + |
| 37 | + if (heap.size() == k) { |
| 38 | + result = Math.max(result, sum * min); |
| 39 | + sum -= heap.dequeue().element; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return result; |
| 44 | +}; |
0 commit comments