![]() |
VOOZH | about |
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.
Table of Content
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.
23
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.
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.
Step 2: Now, multiply elements at the same index of both arrays and compute the sum.
Total sum = 6 + 5 + 12 = 23
23