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
[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
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int maxValue(vector<int> &arr) {
int n = arr.size();
int maxSum = INT_MIN;
// Sort the array first to generate permutations
// in lexicographic order
sort(arr.begin(), arr.end());
// Try all permutations
do {
int currentSum = 0;
// Calculate sum of (element * index) for
// current permutation
for (int i = 0; i < n; i++) {
currentSum += arr[i] * i;
}
// Update maximum sum
if (currentSum > maxSum) {
maxSum = currentSum;
}
} while (next_permutation(arr.begin(), arr.end()));
return maxSum;
}
int main() {
vector<int> arr = {3, 5, 6, 1};
cout << maxValue(arr) << endl;
return 0;
}
// Java program to find maximum sum of (element * index)
import java.util.*;
class GfG {
static int maxValue(int[] arr) {
int n = arr.length;
int maxSum = Integer.MIN_VALUE;
// Sort the array first to generate
// permutations in lexicographic order
Arrays.sort(arr);
// Try all permutations
do {
int currentSum = 0;
// Calculate sum of (element * index)
// for current permutation
for (int i = 0; i < n; i++) {
currentSum += arr[i] * i;
}
// Update maximum sum
if (currentSum > maxSum) {
maxSum = currentSum;
}
} while (nextPermutation(arr));
return maxSum;
}
// Function to generate next permutation
static boolean nextPermutation(int[] arr) {
int i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false;
}
int j = arr.length - 1;
while (arr[j] <= arr[i]) {
j--;
}
// Swap
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// Reverse suffix
int left = i + 1;
int right = arr.length - 1;
while (left < right) {
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return true;
}
// Driver code
public static void main(String[] args) {
int[] arr = {3, 5, 6, 1};
System.out.println(maxValue(arr));
}
}
# Python program to find maximum sum of (element * index)
from itertools import permutations
def maxValue(arr):
n = len(arr)
maxSum = float('-inf')
# Try all permutations
for perm in permutations(arr):
currentSum = 0
# Calculate sum of (element * index) for current permutation
for i in range(n):
currentSum += perm[i] * i
# Update maximum sum
if currentSum > maxSum:
maxSum = currentSum
return maxSum
# Driver code
if __name__ == "__main__":
arr = [3, 5, 6, 1]
print(maxValue(arr))
// C# program to find maximum sum of (element * index)
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
static int maxValue(int[] arr) {
int n = arr.Length;
int maxSum = int.MinValue;
// Sort the array first to generate
// permutations in lexicographic order
Array.Sort(arr);
// Try all permutations
do {
int currentSum = 0;
// Calculate sum of (element * index)
// for current permutation
for (int i = 0; i < n; i++) {
currentSum += arr[i] * i;
}
// Update maximum sum
if (currentSum > maxSum) {
maxSum = currentSum;
}
} while (nextPermutation(arr));
return maxSum;
}
// Function to generate next permutation
static bool nextPermutation(int[] arr) {
int i = arr.Length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false;
}
int j = arr.Length - 1;
while (arr[j] <= arr[i]) {
j--;
}
// Swap
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// Reverse suffix
Array.Reverse(arr, i + 1, arr.Length - i - 1);
return true;
}
// Driver code
static void Main(string[] args) {
int[] arr = {3, 5, 6, 1};
Console.WriteLine(maxValue(arr));
}
}
// JavaScript program to find maximum sum of (element * index)
function maxValue(arr) {
let n = arr.length;
let maxSum = -Infinity;
// Sort the array first to generate permutations
// in lexicographic order
arr.sort((a, b) => a - b);
// Try all permutations
do {
let currentSum = 0;
// Calculate sum of (element * index)
// for current permutation
for (let i = 0; i < n; i++) {
currentSum += arr[i] * i;
}
// Update maximum sum
if (currentSum > maxSum) {
maxSum = currentSum;
}
} while (nextPermutation(arr));
return maxSum;
}
// Function to generate next permutation
function nextPermutation(arr) {
let i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false;
}
let j = arr.length - 1;
while (arr[j] <= arr[i]) {
j--;
}
// Swap
[arr[i], arr[j]] = [arr[j], arr[i]];
// Reverse suffix
let left = i + 1;
let right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return true;
}
// Driver code
const arr = [3, 5, 6, 1];
console.log(maxValue(arr));
[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 + 7to avoid overflow
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int mod = 1e9 + 7;
int maxValue(vector<int> &arr) {
int n = arr.size();
// Sort the array
sort(arr.begin(), arr.end());
// Finding the sum of arr[i]*i
int ans = 0;
for (int i = 0; i < n; i++)
ans = (ans + (1ll * arr[i] * i % mod)) % mod;
return ans;
}
int main() {
vector<int> arr = { 3, 5, 6, 1 };
cout << maxValue(arr) << endl;
return 0;
}
import java.util.Arrays;
class GFG {
static int maxValue(int[] arr) {
int mod = 1000000007;
int n = arr.length;
// Sort the array
Arrays.sort(arr);
// Finding the sum of arr[i]*i
long ans = 0;
for (int i = 0; i < n; i++) {
// Using (long) prevents overflow during multiplication
ans = (ans + ((long) arr[i] * i) % mod) % mod;
}
return (int) ans;
}
public static void main(String[] args) {
int[] arr = { 3, 5, 6, 1 };
System.out.println(maxValue(arr));
}
}
def maxValue(arr):
mod = 10**9 + 7
# Sort the array in-place
arr.sort()
# Finding the sum of arr[i] * i
ans = 0
# enumerate() is a clean, Pythonic way to get both the index (i) and the value
for i, val in enumerate(arr):
ans = (ans + (val * i)) % mod
return ans
if __name__ == "__main__":
arr = [3, 5, 6, 1]
print(maxValue(arr))
using System;
class GFG {
// Function to find the maximum value of i*arr[i]
static int maxValue(int[] arr) {
int mod = 1000000007;
int n = arr.Length;
// Sort the array
Array.Sort(arr);
// Finding the sum of arr[i]*i
long ans = 0;
for (int i = 0; i < n; i++) {
ans = (ans + ((long)arr[i] * i) % mod) % mod;
}
return (int)ans;
}
static public void Main() {
int[] arr = { 3, 5, 6, 1 };
Console.WriteLine(maxValue(arr));
}
}
// JavaScript program to find the maximum value of i*arr[i]
function maxSum(arr) {
// Using BigInt for the modulo to prevent precision loss
const mod = 1000000007n;
// sort the array numerically, not alphabetically
arr.sort((a, b) => a - b);
// Finding the sum of arr[i]*i using BigInt
let ans = 0n;
for (let i = 0; i < arr.length; i++) {
// Convert array value and index to BigInt before multiplication
let val = BigInt(arr[i]);
let idx = BigInt(i);
ans = (ans + (val * idx) % mod) % mod;
}
// Convert back to a standard Number before returning
return Number(ans);
}
// Driver Code
let arr = [ 3, 5, 6, 1 ];
// Using console.log is the modern standard,
// but document.write(maxSum(arr)) works too if running in a browser!
console.log(maxSum(arr));
Output
31