In this approach, the idea is to pair up elements of nums1
and nums2
into tuples. Then, sort these pairs by nums2
in descending order. This way, we process elements with higher values in nums2
first. Using a priority queue (min-heap), we can efficiently keep track of the k largest nums1
values, which we use to calculate the score. The maximum score is computed by iterating through potential minimums, maintaining the current sum of the largest k values seen so far.
Time Complexity: O(n log n) due to sorting and heap operations.
Space Complexity: O(k) for the min-heap storing k elements.
1import heapq
2
3def maxScore(nums1, nums2, k):
4 pairs = sorted(zip(nums2, nums1), reverse=True)
5 min_heap = []
6 current_sum = 0
7 max_score = 0
8 for num2, num1 in pairs:
9 heapq.heappush(min_heap, num1)
10 current_sum += num1
11 if len(min_heap) > k:
12 current_sum -= heapq.heappop(min_heap)
13 if len(min_heap) == k:
14 max_score = max(max_score, current_sum * num2)
15 return max_score
16
17# Example usage
18print(maxScore([1,3,3,2], [2,1,3,4], 3)) # Output: 12
The solution sorts nums2
together with nums1
. It processes from the largest nums2
value, maintaining a sum and a priority queue to track the largest k values of nums1
. The score is calculated as the product of this sum and the current nums2
value in the loop, updating the maximum score as needed.
This approach emphasizes efficient subsequence selection by partitioning the array. Divide the array in such a way that potential results can be directly computed without redundant calculations. Use recursion to evaluate possible subsequences efficiently.
Time Complexity: O(n log n) primary by sorting and heap operations.
Space Complexity: O(k) for the priority queue.
1function maxScore(nums1, nums2, k) {
2 const pairs = nums1.map((num1, i) => [nums2[i], num1]).sort((a, b) => b[0] - a[0]);
3 const minHeap = [];
4 let currentSum = 0, maxScore = 0;
5
6 for (let [num2, num1] of pairs) {
7 minHeap.push(num1);
8 currentSum += num1;
9 if (minHeap.length > k) {
10 currentSum -= Math.min(...minHeap);
11 minHeap.splice(minHeap.indexOf(Math.min(...minHeap)), 1);
12 }
13 if (minHeap.length === k) {
14 maxScore = Math.max(maxScore, currentSum * num2);
15 }
16 }
17
18 return maxScore;
19}
20
21// Example usage
22// console.log(maxScore([1,3,3,2], [2,1,3,4], 3)); // Output: 12
This JavaScript solution employs array methods and manual management of minimum values from min-heap, leveraging native array operations for computing scores.