Maximum sum of pairwise product from two arrays

Last Updated : 22 May, 2026

Given two arrays a[] and b[] of size n containing positive integers. Rearrange the elements of both arrays so that the value of: a[0] * b[0] + a[1] * b[1] + ... + a[n-1] * b[n-1] becomes maximum. Each element of a[] and b[] must be used exactly once.

Examples: 

Input: a[] = [3, 1, 1], b[] = [6, 5, 4]
Output: 27
Explanation: After rearranging: a[] = [1, 1, 3] and b[] = [4, 5, 6]. Maximum sum = (1 * 4) + (1 * 5) + (3 * 6) = 4 + 5 + 18 = 27.

Input: a[] = [1, 2, 3], b[] = [4, 5, 1]
Output: 24
Explanation: After rearranging: a[] = [1, 2, 3] and b[] = [1, 4, 5]. Maximum sum = (1 * 1) + (2 * 4) + (3 * 5) = 1 + 8 + 15 = 24.

Try It Yourself
redirect icon

[Naive Approach] Try All Permutations - O(n! × n!) Time and O(n) Space

The idea is to generate all possible permutations of both arrays and evaluate every possible pairing. For each pair of permutations, we compute the sum of products and select the maximum among all results.

  • Generate all permutations of array a[]
  • Generate all permutations of array b[]
  • For every pair of permutations, compute sum: a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] and return the max of all.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to calculate sum of products
int calc(vector<int> &a, vector<int> &b) {

    int sum = 0;

    for (int i = 0; i < a.size(); i++) {
        sum = (sum + a[i] * b[i]);
    }

    return sum;
}

// Function to generate all permutations of array a[]
void permuteA(vector<int> &a, int idx, vector<vector<int>> &allA) {

    // Base case: if full permutation is formed
    if (idx == a.size()) {
        allA.push_back(a);
        return;
    }

    // Try swapping current index with all positions
    for (int i = idx; i < a.size(); i++) {

        swap(a[i], a[idx]);

        permuteA(a, idx + 1, allA);

        // Backtrack
        swap(a[i], a[idx]);
    }
}

// Function to generate all permutations of array b[]
void permuteB(vector<int> &b, int idx, vector<vector<int>> &allB) {

    // Base case: if full permutation is formed
    if (idx == b.size()) {
        allB.push_back(b);
        return;
    }

    // Try swapping current index with all positions
    for (int i = idx; i < b.size(); i++) {

        swap(b[i], b[idx]);

        permuteB(b, idx + 1, allB);

        // Backtrack
        swap(b[i], b[idx]);
    }
}

int maxProductSum(vector<int> a, vector<int> b) {

    vector<vector<int>> allA, allB;

    // Generate all permutations
    permuteA(a, 0, allA);
    permuteB(b, 0, allB);

    int res = 0;

    // Try every possible pairing
    for (auto &x : allA) {
        for (auto &y : allB) {
            res = max(res, calc(x, y));
        }
    }

    return res;
}

int main() {

    vector<int> a = {3, 1, 1};
    vector<int> b = {6, 5, 4};

    cout << maxProductSum(a, b) << endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

class GFG {

    // Function to calculate sum of products
    static int calc(int[] a, int[] b) {

        int sum = 0;

        for (int i = 0; i < a.length; i++) {
            sum = (sum + a[i] * b[i]);
        }

        return sum;
    }

    // Function to swap elements
    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Function to generate all permutations of array a[]
    static void permuteA(int[] a, int idx, List<int[]> allA) {

        // Base case: if full permutation is formed
        if (idx == a.length) {
            allA.add(a.clone());
            return;
        }

        // Try swapping current index with all positions
        for (int i = idx; i < a.length; i++) {

            swap(a, i, idx);

            permuteA(a, idx + 1, allA);

            // Backtrack
            swap(a, i, idx);
        }
    }

    // Function to generate all permutations of array b[]
    static void permuteB(int[] b, int idx, List<int[]> allB) {

        // Base case: if full permutation is formed
        if (idx == b.length) {
            allB.add(b.clone());
            return;
        }

        // Try swapping current index with all positions
        for (int i = idx; i < b.length; i++) {

            swap(b, i, idx);

            permuteB(b, idx + 1, allB);

            // Backtrack
            swap(b, i, idx);
        }
    }

    static int maxProductSum(int[] a, int[] b) {

        List<int[]> allA = new ArrayList<>();
        List<int[]> allB = new ArrayList<>();

        // Generate all permutations
        permuteA(a, 0, allA);
        permuteB(b, 0, allB);

        int res = 0;

        // Try every possible pairing
        for (int[] x : allA) {
            for (int[] y : allB) {
                res = Math.max(res, calc(x, y));
            }
        }

        return res;
    }

    public static void main(String[] args) {

        int[] a = {3, 1, 1};
        int[] b = {6, 5, 4};

        System.out.println(maxProductSum(a, b));
    }
}
Python
# Function to calculate sum of products
def calc(a, b):

    sum = 0

    for i in range(len(a)):
        sum = (sum + a[i] * b[i])

    return sum


# Function to generate all permutations of array a[]
def permuteA(a, idx, allA):

    # Base case: if full permutation is formed
    if idx == len(a):
        allA.append(a[:])
        return

    # Try swapping current index with all positions
    for i in range(idx, len(a)):

        a[i], a[idx] = a[idx], a[i]

        permuteA(a, idx + 1, allA)

        # Backtrack
        a[i], a[idx] = a[idx], a[i]


# Function to generate all permutations of array b[]
def permuteB(b, idx, allB):

    # Base case: if full permutation is formed
    if idx == len(b):
        allB.append(b[:])
        return

    # Try swapping current index with all positions
    for i in range(idx, len(b)):

        b[i], b[idx] = b[idx], b[i]

        permuteB(b, idx + 1, allB)

        # Backtrack
        b[i], b[idx] = b[idx], b[i]


def maxProductSum(a, b):

    allA = []
    allB = []

    # Generate all permutations
    permuteA(a, 0, allA)
    permuteB(b, 0, allB)

    res = 0

    # Try every possible pairing
    for x in allA:
        for y in allB:
            res = max(res, calc(x, y))

    return res


if __name__ == "__main__":

    a = [3, 1, 1]
    b = [6, 5, 4]

    print(maxProductSum(a, b))
C#
using System;
using System.Collections.Generic;

class GFG {

    // Function to calculate sum of products
    static int calc(List<int> a, List<int> b) {

        int sum = 0;

        for (int i = 0; i < a.Count; i++) {
            sum = (sum + a[i] * b[i]);
        }

        return sum;
    }

    // Function to generate all permutations of array a[]
    static void permuteA(List<int> a, int idx, List<List<int>> allA) {

        // Base case: if full permutation is formed
        if (idx == a.Count) {
            allA.Add(new List<int>(a));
            return;
        }

        // Try swapping current index with all positions
        for (int i = idx; i < a.Count; i++) {

            int temp = a[i];
            a[i] = a[idx];
            a[idx] = temp;

            permuteA(a, idx + 1, allA);

            // Backtrack
            temp = a[i];
            a[i] = a[idx];
            a[idx] = temp;
        }
    }

    // Function to generate all permutations of array b[]
    static void permuteB(List<int> b, int idx, List<List<int>> allB) {

        // Base case: if full permutation is formed
        if (idx == b.Count) {
            allB.Add(new List<int>(b));
            return;
        }

        // Try swapping current index with all positions
        for (int i = idx; i < b.Count; i++) {

            int temp = b[i];
            b[i] = b[idx];
            b[idx] = temp;

            permuteB(b, idx + 1, allB);

            // Backtrack
            temp = b[i];
            b[i] = b[idx];
            b[idx] = temp;
        }
    }

    static int maxProductSum(List<int> a, List<int> b) {

        List<List<int>> allA = new List<List<int>>();
        List<List<int>> allB = new List<List<int>>();

        // Generate all permutations
        permuteA(a, 0, allA);
        permuteB(b, 0, allB);

        int res = 0;

        // Try every possible pairing
        foreach (List<int> x in allA) {
            foreach (List<int> y in allB) {
                res = Math.Max(res, calc(x, y));
            }
        }

        return res;
    }

    static void Main() {

        List<int> a = new List<int>() { 3, 1, 1 };
        List<int> b = new List<int>() { 6, 5, 4 };

        Console.WriteLine(maxProductSum(a, b));
    }
}
JavaScript
// Function to calculate sum of products
function calc(a, b) {

    let sum = 0;

    for (let i = 0; i < a.length; i++) {
        sum = (sum + a[i] * b[i]);
    }

    return sum;
}

// Function to generate all permutations of array a[]
function permuteA(a, idx, allA) {

    // Base case: if full permutation is formed
    if (idx === a.length) {
        allA.push([...a]);
        return;
    }

    // Try swapping current index with all positions
    for (let i = idx; i < a.length; i++) {

        [a[i], a[idx]] = [a[idx], a[i]];

        permuteA(a, idx + 1, allA);

        // Backtrack
        [a[i], a[idx]] = [a[idx], a[i]];
    }
}

// Function to generate all permutations of array b[]
function permuteB(b, idx, allB) {

    // Base case: if full permutation is formed
    if (idx === b.length) {
        allB.push([...b]);
        return;
    }

    // Try swapping current index with all positions
    for (let i = idx; i < b.length; i++) {

        [b[i], b[idx]] = [b[idx], b[i]];

        permuteB(b, idx + 1, allB);

        // Backtrack
        [b[i], b[idx]] = [b[idx], b[i]];
    }
}

function maxProductSum(a, b) {

    let allA = [];
    let allB = [];

    // Generate all permutations
    permuteA(a, 0, allA);
    permuteB(b, 0, allB);

    let res = 0;

    // Try every possible pairing
    for (let x of allA) {
        for (let y of allB) {
            res = Math.max(res, calc(x, y));
        }
    }

    return res;
}

// Driver code
let a = [3, 1, 1];
let b = [6, 5, 4];
console.log(maxProductSum(a, b));

Output
27

[Expected Approach] Sorting + Greedy - O(n log n) Time and O(1) Space

To maximize the sum of products, we maximize the contribution of larger elements. Since larger elements have a higher impact on the final result, they should be paired with other larger elements.

To achieve this, we sort both arrays in increasing order. This ensures that large elements are multiplied with large elements, which leads to the maximum possible sum of products.

  • Sort array a[] in increasing order.
  • Sort array b[] in increasing order.
  • Initialize sum = 0, traverse both arrays and update sum += a[i] * b[i]

Consider: a[] = {3, 1, 1} and b[] = {6, 5, 4}

Step 1: To maximize the sum, we first sort both arrays in increasing order.

  • a[] = {1, 1, 3}
  • b[] = {4, 5, 6}

Step 2: Now, multiply elements at the same index of both arrays and compute the sum.

  • i = 0 -> 1 × 4 = 4
  • i = 1 -> 1 × 5 = 5
  • i = 2 -> 3 × 6 = 18

Total sum = 4 + 5 + 18 = 27

C++
#include <bits/stdc++.h>
using namespace std;

int maxProductSum(vector<int> &a, vector<int> &b)
{
    // Sort both arrays in increasing order
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());

    int sum = 0;

    // Multiply corresponding elements
    for (int i = 0; i < a.size(); i++)
    {
        sum = sum + a[i] * b[i];
    }

    return sum;
}

int main()
{

    vector<int> a = {3, 1, 1};
    vector<int> b = {6, 5, 4};

    cout << maxProductSum(a, b) << endl;

    return 0;
}
Java
import java.util.Arrays;

class GFG {

    public static int maxProductSum(int[] a, int[] b)
    {
        // Sort both arrays in increasing order
        Arrays.sort(a);
        Arrays.sort(b);

        int sum = 0;

        // Multiply corresponding elements
        for (int i = 0; i < a.length; i++) {
            sum = sum + a[i] * b[i];
        }

        return sum;
    }

    public static void main(String[] args)
    {

        int[] a = { 3, 1, 1 };
        int[] b = { 6, 5, 4 };

        System.out.println(maxProductSum(a, b));
    }
}
Python
def maxProductSum(a, b):
    
    # Sort both arrays in increasing order
    a.sort()
    b.sort()

    sum = 0

    # Multiply corresponding elements
    for i in range(len(a)):
        sum = sum + a[i] * b[i]

    return sum

if __name__ == "__main__":

    a = [3, 1, 1]
    b = [6, 5, 4]

    print(maxProductSum(a, b))
C#
using System;

class GFG {

    static int maxProductSum(int[] a, int[] b)
    {
        // Sort both arrays in increasing order
        Array.Sort(a);
        Array.Sort(b);

        int sum = 0;

        // Multiply corresponding elements
        for (int i = 0; i < a.Length; i++) {
            sum = sum + a[i] * b[i];
        }

        return sum;
    }

    static void Main()
    {

        int[] a = { 3, 1, 1 };
        int[] b = { 6, 5, 4 };

        Console.WriteLine(maxProductSum(a, b));
    }
}
JavaScript
function maxProductSum(a, b) {

    // Sort both arrays in increasing order
    a.sort((x, y) => x - y);
    b.sort((x, y) => x - y);

    let sum = 0;

    // Multiply corresponding elements
    for (let i = 0; i < a.length; i++) {
        sum = sum + a[i] * b[i];
    }

    return sum;
}

// Drive code
let a = [3, 1, 1];
let b = [6, 5, 4];

console.log(maxProductSum(a, b));

Output
27
Comment