![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements