Open In App

K maximum sum combinations from two arrays

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integer arrays A and B of size N each. A sum combination is made by adding one element from array A and another element of array B. The task is to return the maximum K valid sum combinations from all the possible sum combinations.

Note: Output array must be sorted in non-increasing order.

Examples:

Input: N = 2, K = 2, A[ ] = {3, 2}, B[ ] = {1, 4}
Output: {7, 6}
Explanation:  7 -> (A : 3) + (B : 4)
6 -> (A : 2) + (B : 4)

Input: N = 4, K = 3, A [ ] = {1, 4, 2, 3}, B [ ] = {2, 5, 1, 6}
Output: {10, 9, 9}
Explanation: 10 -> (A : 4) + (B : 6)
9 -> (A : 4) + (B : 5)
9 -> (A : 3) + (B : 6)


[Naive Approach] Generate All Combinations - O(N^2 * log(N^2)) Time and O(N^2) Space

The idea is to generate all possible sum combinations of elements from arrays A and B, storing them in a list. Since each element from A can pair with every element from B, we use a nested loop to compute all sums. We then sort this list in descending order to prioritize larger sums. Finally, we extract the top K values from the sorted list, ensuring we get the K highest sum combinations efficiently.

C++
// C++ program to find N maximum combinations
// from two arrays by generating all combinations
#include <bits/stdc++.h>
using namespace std;

vector<int> maxCombinations(int N, int K, 
                  vector<int> &A, vector<int> &B) {
    vector<int> sums;

    // Compute all possible sum combinations
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            sums.push_back(A[i] + B[j]);
        }
    }

    // Sort in non-increasing order
    sort(sums.begin(), sums.end(), greater<int>());

    vector<int> topK;

    // Select the top K sums
    for (int i = 0; i < K; i++) {
        topK.push_back(sums[i]);
    }

    return topK;
}

void printArr(vector<int> &arr) {
    for (int num : arr) {
        cout << num << " ";
    }
    cout << endl;
}

// Driver code
int main() {
    int N = 2, K = 2;
    vector<int> A = {3, 2}, B = {1, 4};

    vector<int> result = maxCombinations(N, K, A, B);
    
    printArr(result);

    return 0;
}
Java
// Java program to find N maximum combinations
// from two arrays by generating all combinations
import java.util.*;

class GfG {
    
    static List<Integer> maxCombinations(int N, int K, 
                              int A[], int B[]) {
        List<Integer> sums = new ArrayList<>();

        // Compute all possible sum combinations
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                sums.add(A[i] + B[j]);
            }
        }

        // Sort in non-increasing order
        sums.sort(Collections.reverseOrder());

        List<Integer> topK = new ArrayList<>();

        // Select the top K sums
        for (int i = 0; i < K; i++) {
            topK.add(sums.get(i));
        }

        return topK;
    }

    static void printArr(List<Integer> arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    // Driver code
    public static void main(String[] args) {
        int N = 2, K = 2;
        int A[] = {3, 2}, B[] = {1, 4};

        List<Integer> result = maxCombinations(N, K, A, B);
        
        printArr(result);
    }
}
Python
# Python program to find N maximum combinations
# from two arrays by generating all combinations

def maxCombinations(N, K, A, B):
    sums = []

    # Compute all possible sum combinations
    for i in range(N):
        for j in range(N):
            sums.append(A[i] + B[j])

    # Sort in non-increasing order
    sums.sort(reverse=True)

    topK = []

    # Select the top K sums
    for i in range(K):
        topK.append(sums[i])

    return topK

def printArr(arr):
    for num in arr:
        print(num, end=" ")
    print()

# Driver code
if __name__ == "__main__":
    N, K = 2, 2
    A = [3, 2]
    B = [1, 4]

    result = maxCombinations(N, K, A, B)
    
    printArr(result)
C#
// C# program to find N maximum combinations
// from two arrays by generating all combinations
using System;
using System.Collections.Generic;

class GfG {
    
    static List<int> MaxCombinations(int N, int K, 
                           int[] A, int[] B) {
        List<int> sums = new List<int>();

        // Compute all possible sum combinations
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                sums.Add(A[i] + B[j]);
            }
        }

        // Sort in non-increasing order
        sums.Sort((a, b) => b.CompareTo(a));

        List<int> topK = new List<int>();

        // Select the top K sums
        for (int i = 0; i < K; i++) {
            topK.Add(sums[i]);
        }

        return topK;
    }

    static void PrintArr(List<int> arr) {
        foreach (int num in arr) {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }

    // Driver code
    static void Main() {
        int N = 2, K = 2;
        int[] A = {3, 2}, B = {1, 4};

        List<int> result = MaxCombinations(N, K, A, B);
        
        PrintArr(result);
    }
}
JavaScript
// JavaScript program to find N maximum combinations
// from two arrays by generating all combinations

function maxCombinations(N, K, A, B) {
    let sums = [];

    // Compute all possible sum combinations
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < N; j++) {
            sums.push(A[i] + B[j]);
        }
    }

    // Sort in non-increasing order
    sums.sort((a, b) => b - a);

    let topK = [];

    // Select the top K sums
    for (let i = 0; i < K; i++) {
        topK.push(sums[i]);
    }

    return topK;
}

function printArr(arr) {
    console.log(arr.join(" "));
}

// Driver code
let N = 2, K = 2;
let A = [3, 2], B = [1, 4];

let result = maxCombinations(N, K, A, B);

printArr(result);

Output
7 6 

[Expected Approach] Using Sorting + Heap + Set - O(N * logN) Time and O(N) Space

The idea is to use a max heap (priority queue). First, we sort both arrays in descending order so that the largest possible sums appear first. We then use a max heap to track the highest sum combinations, starting with the largest sum from A[0] + B[0]. At each step, we extract the maximum sum and push the next possible sums by incrementing the indices, ensuring that we always get the next largest sum efficiently. A set is used to track visited pairs, preventing duplicate computations.

Steps to implement the above idea:

  • Sort both arrays in descending order to prioritize larger sums.
  • Initialize a max heap and insert the largest sum combination along with its indices.
  • Use a set to track visited index pairs and avoid duplicates.
  • Extract the largest sum from the heap, store it in the result, and push new valid combinations.
  • Push the next possible sums by incrementing either index and check if they are already used.
  • Repeat for K iterations to get the K largest sum combinations.
C++
// C++ program to find N maximum combinations
// using a max heap for an O(N log N) approach
#include <bits/stdc++.h>
using namespace std;

vector<int> maxCombinations(int N, int K, 
              vector<int> &A, vector<int> &B) {
                  
    // Sort both arrays in descending order
    sort(A.rbegin(), A.rend());
    sort(B.rbegin(), B.rend());

    // Max heap to store {sum, {i, j}}
    priority_queue<pair<int, pair<int, int>>> maxHeap;
    set<pair<int, int>> used;

    // Push the largest sum combination
    maxHeap.push({A[0] + B[0], {0, 0}});
    used.insert({0, 0});

    vector<int> topK;

    // Extract K maximum sum combinations
    for (int count = 0; count < K; count++) {
        // Extract top element
        pair<int, pair<int, int>> top = maxHeap.top();
        maxHeap.pop();

        int sum = top.first;
        int i = top.second.first, j = top.second.second;

        topK.push_back(sum);

        // Push next combination (i+1, j) if within bounds and not used
        if (i + 1 < N && used.find({i + 1, j}) == used.end()) {
            maxHeap.push({A[i + 1] + B[j], {i + 1, j}});
            used.insert({i + 1, j});
        }

        // Push next combination (i, j+1) if within bounds and not used
        if (j + 1 < N && used.find({i, j + 1}) == used.end()) {
            maxHeap.push({A[i] + B[j + 1], {i, j + 1}});
            used.insert({i, j + 1});
        }
    }

    return topK;
}

void printArr(vector<int> &arr) {
    for (int num : arr) {
        cout << num << " ";
    }
    cout << endl;
}

// Driver code
int main() {
    int N = 2, K = 2;
    vector<int> A = {3, 2}, B = {1, 4};

    vector<int> result = maxCombinations(N, K, A, B);
    
    printArr(result);

    return 0;
}
Java
// Java program to find N maximum combinations
// using a max heap for an O(N log N) approach
import java.util.*;

class GfG {
    static List<Integer> maxCombinations(int N, int K,
                                   int A[], int B[]) {
                                       
        // Sort both arrays in descending order
        Arrays.sort(A);
        Arrays.sort(B);
        reverse(A);
        reverse(B);

        // Max heap to store {sum, {i, j}}
        PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
            (a, b) -> Integer.compare(b[0], a[0])
        );
        Set<String> used = new HashSet<>();

        // Push the largest sum combination
        maxHeap.offer(new int[]{A[0] + B[0], 0, 0});
        used.add("0,0");

        List<Integer> topK = new ArrayList<>();

        // Extract K maximum sum combinations
        for (int count = 0; count < K; count++) {
            // Extract top element
            int[] top = maxHeap.poll();
            int sum = top[0];
            int i = top[1], j = top[2];

            topK.add(sum);

            // Push next combination (i+1, j) if within bounds and not used
            if (i + 1 < N && !used.contains((i + 1) + "," + j)) {
                maxHeap.offer(new int[]{A[i + 1] + B[j], i + 1, j});
                used.add((i + 1) + "," + j);
            }

            // Push next combination (i, j+1) if within bounds and not used
            if (j + 1 < N && !used.contains(i + "," + (j + 1))) {
                maxHeap.offer(new int[]{A[i] + B[j + 1], i, j + 1});
                used.add(i + "," + (j + 1));
            }
        }

        return topK;
    }

    static void reverse(int[] arr) {
        int l = 0, r = arr.length - 1;
        while (l < r) {
            int temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            l++;
            r--;
        }
    }

    static void printArr(List<Integer> arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    // Driver code
    public static void main(String[] args) {
        int N = 2, K = 2;
        int A[] = {3, 2}, B[] = {1, 4};

        List<Integer> result = maxCombinations(N, K, A, B);

        printArr(result);
    }
}
Python
# Python program to find N maximum combinations
# using a max heap for an O(N log N) approach
import heapq

def maxCombinations(N, K, A, B):
    
    # Sort both arrays in descending order
    A.sort(reverse=True)
    B.sort(reverse=True)

    # Max heap to store (-sum, i, j) since heapq is a min heap
    maxHeap = []
    used = set()

    # Push the largest sum combination
    heapq.heappush(maxHeap, (-(A[0] + B[0]), 0, 0))
    used.add((0, 0))

    topK = []

    # Extract K maximum sum combinations
    for _ in range(K):
        # Extract top element
        sum_neg, i, j = heapq.heappop(maxHeap)
        sum = -sum_neg  # Convert back to positive

        topK.append(sum)

        # Push next combination (i+1, j) if within bounds and not used
        if i + 1 < N and (i + 1, j) not in used:
            heapq.heappush(maxHeap, (-(A[i + 1] + B[j]), i + 1, j))
            used.add((i + 1, j))

        # Push next combination (i, j+1) if within bounds and not used
        if j + 1 < N and (i, j + 1) not in used:
            heapq.heappush(maxHeap, (-(A[i] + B[j + 1]), i, j + 1))
            used.add((i, j + 1))

    return topK

def printArr(arr):
    print(" ".join(map(str, arr)))

# Driver code
if __name__ == "__main__":
    N, K = 2, 2
    A = [3, 2]
    B = [1, 4]

    result = maxCombinations(N, K, A, B)

    printArr(result)
C#
// C# program to find N maximum combinations
// using a max heap for an O(N log N) approach
using System;
using System.Collections.Generic;

class GfG {
    static List<int> MaxCombinations(int N, int K, int[] A, int[] B) {
        // Sort both arrays in descending order
        Array.Sort(A);
        Array.Sort(B);
        Array.Reverse(A);
        Array.Reverse(B);

        // Max heap using SortedSet
        SortedSet<(int, int, int)> maxHeap = 
            new SortedSet<(int, int, int)>(Comparer<(int, int, int)>
            .Create((a, b) => a.Item1 != b.Item1 ? 
                b.Item1.CompareTo(a.Item1) : 
                a.Item2 != b.Item2 ? a.Item2.CompareTo(b.Item2) : 
                a.Item3.CompareTo(b.Item3)));

        HashSet<string> used = new HashSet<string>();

        // Push the largest sum combination
        maxHeap.Add((A[0] + B[0], 0, 0));
        used.Add("0,0");

        List<int> topK = new List<int>();

        // Extract K maximum sum combinations
        for (int count = 0; count < K; count++) {
            // Extract top element
            var top = maxHeap.Min;
            maxHeap.Remove(top);

            int sum = top.Item1;
            int i = top.Item2, j = top.Item3;

            topK.Add(sum);

            // Push next combination (i+1, j) if within bounds and not used
            if (i + 1 < N && !used.Contains((i + 1) + "," + j)) {
                maxHeap.Add((A[i + 1] + B[j], i + 1, j));
                used.Add((i + 1) + "," + j);
            }

            // Push next combination (i, j+1) if within bounds and not used
            if (j + 1 < N && !used.Contains(i + "," + (j + 1))) {
                maxHeap.Add((A[i] + B[j + 1], i, j + 1));
                used.Add(i + "," + (j + 1));
            }
        }

        return topK;
    }

    static void PrintArr(List<int> arr) {
        foreach (int num in arr) {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }

    // Driver code
    static void Main() {
        int N = 2, K = 2;
        int[] A = {3, 2}, B = {1, 4};

        List<int> result = MaxCombinations(N, K, A, B);

        PrintArr(result);
    }
}
JavaScript
// JavaScript program to find N maximum combinations
// using a max heap for an O(N log N) approach

class MaxHeap {
    constructor() {
        this.heap = [];
    }

    push(element) {
        this.heap.push(element);
        
        // Sort in descending order
        this.heap.sort((a, b) => b[0] - a[0]); 
    }

    pop() {
        return this.heap.shift();
    }

    top() {
        return this.heap[0];
    }

    size() {
        return this.heap.length;
    }
}

function maxCombinations(N, K, A, B) {
    // Sort both arrays in descending order
    A.sort((a, b) => b - a);
    B.sort((a, b) => b - a);

    // Max heap to store [sum, i, j]
    let maxHeap = new MaxHeap();
    let used = new Set();

    // Push the largest sum combination
    maxHeap.push([A[0] + B[0], 0, 0]);
    used.add(`0,0`);

    let topK = [];

    // Extract K maximum sum combinations
    for (let count = 0; count < K; count++) {
        // Extract top element
        let [sum, i, j] = maxHeap.pop();

        topK.push(sum);

        // Push next combination (i+1, j) if within bounds and not used
        if (i + 1 < N && !used.has(`${i + 1},${j}`)) {
            maxHeap.push([A[i + 1] + B[j], i + 1, j]);
            used.add(`${i + 1},${j}`);
        }

        // Push next combination (i, j+1) if within bounds and not used
        if (j + 1 < N && !used.has(`${i},${j + 1}`)) {
            maxHeap.push([A[i] + B[j + 1], i, j + 1]);
            used.add(`${i},${j + 1}`);
        }
    }

    return topK;
}

function printArr(arr) {
    console.log(arr.join(" "));
}

// Driver code
let N = 2, K = 2;
let A = [3, 2], B = [1, 4];

let result = maxCombinations(N, K, A, B);

printArr(result);

Output
7 6 



Next Article
Article Tags :
Practice Tags :

Similar Reads