VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-sum-arrii/

⇱ Max Sum of i*arr[i] with Rearrangement - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Max Sum of i*arr[i] with Rearrangement

Last Updated : 26 May, 2026

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 maximum

Input: arr[] = [19, 20]
Output: 20

[Brute Force] All Permutations – O(n! × n) Time and O(1) Extra Space

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.

  • Sort the array initially
  • Generate all possible permutations using next_permutation()
  • For every permutation: Calculate the weighted sum arr[i] * i and update the maximum value obtained


[Expected Approach] Sorting - O(n Log n) Time and O(1) Space

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:

  • Sort the array in ascending order
  • Traverse the array: Multiply each element with its index and add the result to the answer
  • Take modulo 1e9 + 7 to avoid overflow

Output
31
Comment
Article Tags: