The K Maximum Sum Combinations From Two Arrays problem involves finding the top K
largest sums that can be formed by picking one element from each of two arrays.
This problem can be solved using a max-heap to track the largest sums.
class Solution {
public List<Integer> kMaxSumCombinations(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
(a, b) -> b[0] - a[0]
);
Arrays.sort(nums1);
Arrays.sort(nums2);
for (int i = nums1.length - 1; i >= 0; i--) {
maxHeap.offer(new int[]{nums1[i] + nums2[nums2.length - 1], i, nums2.length - 1});
}
List<Integer> result = new ArrayList<>();
while (k > 0 && !maxHeap.isEmpty()) {
int[] top = maxHeap.poll();
result.add(top[0]);
k--;
int i = top[1], j = top[2];
if (j > 0) {
maxHeap.offer(new int[]{nums1[i] + nums2[j - 1], i, j - 1});
}
}
return result;
}
}
O(N log N + M log M)
โ Sorting both arrays.O(K log K)
โ Adding and removing elements from the heap.O(N log N + M log M + K log K)
.Input: nums1 = [1, 4, 2], nums2 = [3, 5], k = 3
Output: [9, 8, 7]
Explanation:
- The top 3 sums are [9, 8, 7].