![]() |
VOOZH | about |
Given two integer arrays a[] and b[] of the same length, and an positive integer k, the goal is to find the top k maximum sum combinations, where each combination is formed by adding one element from a and one from b.
Each index from both arrays can be used at most once in a pair. Return the k largest sums in descending order.
Examples:
Input: a[] = [3, 2], b[] = [1, 4], k = 2
Output: [7, 6]
Explanation: Possible sums: 3 + 1 = 4, 3 + 4 = 7, 2 + 1 = 3, 2 + 4 = 6, Top 2 sums are 7 and 6.Input: a[] = [1, 4, 2, 3], b[] = [2, 5, 1, 6], k = 3
Output: [10, 9, 9]
Explanation: The top 3 maximum possible sums are : 4 + 6 = 10, 3 + 6 = 9, and 4 + 5 = 9.
Table of Content
The idea is to compute all possible sum combinations by pairing each element from array
a[]with every element from arrayb[]. Since each element inacan form a pair with every element inb, we use a nested loop to generate all such sums. After generating these sums, we sort them in descending order and collect the topkvalues as the final result.
10 9 9
The idea is to generate all possible pair sums by adding each element from array
a[]to each element from arrayb[]. A min-heap of sizekis used to maintain the topkmaximum sums. For every new pair sum, we insert it into the heap if itβs among the largestkseen so far. Finally, we extract and reverse the heap to return the topksums in descending order.
7 6
The idea is to combine the largest elements from both arrays to form the highest possible sums. By sorting the arrays in descending order, we ensure that the sum at indices (0, 0) is the maximum. From this point, the next potential largest sums lie at positions (i+1, j) and (i, j+1) because of the sorted order. By exploring these candidates using a max heap and tracking visited index pairs, we efficiently gather the top k combinations without redundantly computing all n2 possibilities.
Steps by step approach:
a[] and b[] in descending order to ensure the largest sums are considered first.(a[0] + b[0]) along with their indices (0, 0).k iterations to extract the top k sums:(i+1, j) and (i, j+1) into the heap if within bounds and not visited.10 9 9