Problem Description
Given two 0-indexed integer arrays, nums1 and nums2, of equal length n and an integer k, choose a subsequence of indices of length k. The score for a chosen subsequence is defined as the sum of the selected elements from nums1 multiplied by the minimum of the corresponding elements from nums2. The goal is to return the maximum possible score.
Key Insights
- The score is determined by both the sum of selected nums1 elements and the minimum of the selected nums2 elements.
- Sorting pairs of (nums2, nums1) in descending order by their nums2 values lets you control the minimum value in any selected group.
- By iterating through these sorted pairs, each candidate's nums2 becomes the current “minimum” in the candidate group.
- Maintain a min-heap (priority queue) for the k highest nums1 values encountered so far to maximize the sum.
- When the heap size exceeds k, remove the smallest nums1 value to keep only the k best contributions.
- Calculate the score as (current sum of heap) * (current nums2) each time the heap size equals k, and update the maximum score.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting and O(n log k) for heap operations, resulting overall in O(n log n). Space Complexity: O(n) for storing pairs and O(k) for the heap.
Solution
The solution involves first pairing elements from nums2 and nums1 and then sorting these pairs in descending order based on nums2. This ensures that as you iterate, the current nums2 value is the minimum for the candidate subsequence. A min-heap is used to always maintain the k largest nums1 values encountered so far. By iterating through the sorted pairs, you update a running sum of nums1 values and calculate the score whenever exactly k elements have been selected. The maximum score found during the process is returned as the solution.