VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-sum-product-two-arrays-permutations-allowed/

⇱ Minimize the sum of product - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize the sum of product

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 minimum. Each element of a[] and b[] must be used exactly once.

Examples:

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

Input: a[] = [6, 1, 9, 5, 4] , b[] = [3, 4, 8, 2, 4]
Output: 80
Explanation: After rearranging: a[] = [1, 4, 5, 6, 9] and b[] = [8, 4, 4, 3, 2]. Minimum sum = (1 * 8) + (4 * 4) + (5 * 4) + (6 * 3) + (9 * 2) = 8 + 16 + 20 + 18 + 18 = 80.

[Naive Approach] Try All Permutations - O(n! × n!) Time 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 minimum 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]
  • Keep track of the minimum sum obtained.

Output
23

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

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

To achieve this, we sort one array in increasing order and the other in decreasing order. This ensures that each large element is multiplied with a small element, which reduces its contribution and leads to the minimum possible sum of products.

  • Sort array a[] in increasing order.
  • Sort array b[] in decreasing order.
  • Initialize sum = 0.
  • Traverse both arrays: sum += a[i] * b[i]
  • Return sum.

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

Step 1: To minimize the sum, we first sort array a[] in increasing order and array b[] in decreasing order.

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

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

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

Total sum = 6 + 5 + 12 = 23


Output
23
Comment
Article Tags: