![]() |
VOOZH | about |
Given an array of n integers, the task is to maximize the value of the product of each array element with their corresponding indices by rearranging the array. We mainly need to maximize ∑arr[i]×i for every index i.
Examples:
Input: arr[] = [3, 5, 6, 1]
Output: 31
Explanation: If we arrange arr[] as [1, 3, 5, 6 ]. Sum of arr[i]*i is 1*0 + 3*1 + 5*2 + 6*3 = 31, which is maximumInput: arr[] = [19, 20]
Output: 20
Table of Content
The idea is to generate every possible permutation of the array and calculate the value of: ∑arr[i]×i , for each arrangement. Since different permutations produce different weighted sums, every permutation is checked to find the maximum possible value. The array is first sorted so that
next_permutation()can generate all permutations systematically in lexicographical order.
next_permutation()arr[i] * i and update the maximum value obtained The idea is to maximize the value of: ∑arr[i]×i , To achieve the maximum sum, larger elements should be multiplied by larger indices because higher indices contribute more to the final value. Therefore, the array is sorted in ascending order so that smaller elements get smaller multipliers and larger elements get larger multipliers.
Follow the steps mentioned below to implement the idea:
1e9 + 7 to avoid overflow 31