Skip to content

Commit 5acf477

Browse files
committed
Add solution #2542
1 parent 8025350 commit 5acf477

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,7 @@
541541
2493|[Divide Nodes Into the Maximum Number of Groups](./2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
542542
2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
543543
2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
544+
2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium|
544545
2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium|
545546
2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy|
546547
2620|[Counter](./2620-counter.js)|Easy|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)