Rearrange an Array to Maximize i*arr[i] using C++

C++Server Side ProgrammingProgramming

In this article, we will discuss the problem of rearranging a given array of n numbers. Basically, we have to select elements from the array. For selecting each element, we get some points that will be evaluated by the value of the current element * a number of elements selected before the current element. You should select elements to get maximum points. For Example −

Input : arr[ ] = { 3, 1, 5, 6, 3 }

If we select the elements in the way it is given, our points will be
   = 3 * 0 + 1 * 1 + 5 * 2 + 6 * 3 + 3 * 4
   = 41
To maximize the points we have to select the elements in order { 1, 3, 3, 5, 6 }
   = 1 * 0 + 3 * 1 + 3 * 2 + 5 * 3 + 6 * 4
   = 48(maximum)

Output : 48

Input : arr[ ] = { 2, 4, 7, 1, 8 }
Output : 63

Approach to find The Solution

Looking at the example, we got that to get the maximum points, and we need to select elements from smallest to largest. The approach to finding a solution is,

  • Sort the given array in ascending order.
  • Start picking elements from index 0 to end.
  • Calculate the points you got from selecting each element.

Example

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

int main () {
   int arr[] = { 2, 4, 7, 1, 8 };
   int n = sizeof (arr) / sizeof (arr[0]);
   // sorting the array
   sort (arr, arr + n);

   int points = 0;
   // traverse the array and calculate the points
   for (int i = 0; i < n; i++) {
      points += arr[i] * i;
   }
   cout << "Maximum points: " << points;
   return 0;
}

Output

Maximum points: 63

Explanation of the above code

This C++ code is easy to understand. First we are sorting the array and then traverse the array using a for loop and calculating the points gained by selecting each element from beginning to end.

Conclusion

In this article, we discuss the problem of selecting element in an array in order to get maximum points where points get calculated by i * arr[i]. We apply a greedy approach to solve this problem and get the maximum points. Also discuss C++ code to do the same, we can write this code in any other language like C, java, Python, etc. Hope you find this article helpful.

raja
Updated on 26-Nov-2021 10:41:11

Advertisements