Maximize the sum of arr[i]*i in C++


Problem statement

Given an array of N integers. You are allowed to rearrange the elements of the array. The task is to find the maximum value of Σarr[i]*i, where i = 0, 1, 2, .. n – 1.

If input array = {4, 1, 6, 2} then the maximum sum will be 28 if we rearrange elements in sorted order−

{1, 2, 4, 6} = (1 * 0) + (2 * 1) + (4 * 2) + (6 * 3) = 28

Algorithm

1. Sort array in ascending order
2. Iterate over array and multiply each array element by 1 where i = 0, 1, 2, n – 1.
3. Return sum

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxSum(int *arr, int n){
   sort(arr, arr + n);
   int sum = 0;
   for (int i = 0; i < n; ++i) {
      sum = sum + arr[i] * i;
   }
   return sum;
}
int main(){
   int arr[] = {4, 1, 6, 2};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Maximum sum = " << getMaxSum(arr, n) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates following output−

Maximum sum = 28

Updated on: 24-Dec-2019

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements