For example if A = [1,2], B = [3,4], then possible pair sums can be 1+3 = 4 , 1+4=5 , 2+3=5 , 2+4=6
and maximum 2 elements are 6, 5
Maximum 4 elements of combinations sum are
10 (4+6),
9 (3+6),
9 (4+5),
8 (2+6)
public class Solution {
public int[] solve(int[] A, int[] B) {
Arrays.sort(A);
Arrays.sort(B);
PriorityQueue<ArrayList<Integer>> pq = new PriorityQueue<>((a, b) -> b.get(0) + b.get(1) - a.get(0) - a.get(1));
for (int i = 0; i < A.length; i++) {
ArrayList<Integer> temp = new ArrayList<>();
temp.addAll(Arrays.asList(A[i], B[B.length - 1], B.length - 1));
pq.add(temp);
}
int[] ans = new int[A.length];
int counter = A.length, index = 0;
while (counter-- > 0 && pq.size() != 0) {
ArrayList<Integer> temp = pq.poll();
ans[index++] = temp.get(0) + temp.get(1);
if (temp.get(2) == 0) {
continue;
}
ArrayList<Integer> temp2 = new ArrayList<>();
temp2.addAll(Arrays.asList(temp.get(0), B[temp.get(2) - 1], temp.get(2) - 1));
pq.add(temp2);
}
return ans;
}
}