![]() |
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 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.
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 maximum among all results.
27
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.
Consider: a[] = {3, 1, 1} and b[] = {6, 5, 4}
Step 1: To maximize the sum, we first sort both arrays in increasing order.
Step 2: Now, multiply elements at the same index of both arrays and compute the sum.
Total sum = 4 + 5 + 18 = 27
27