VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-of-products-of-two-arrays/

⇱ Maximum sum of pairwise product from two arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

[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.

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


Output
27
Comment
Article Tags: