- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Maximize value of (arr[i] – i) – (arr[j] – j) in an array in C++
- Maximize arr[j] – arr[i] + arr[l] – arr[k], such that i < j < k < l in C++
- Rearrange an Array to Maximize i*arr[i] using C++
- Count number of pairs (i, j) such that arr[i] * arr[j] > arr[i] + arr[j] in C++
- Maximum value of |arr[i] – arr[j] - + |i – j| in C++
- Maximum sum of i * arr[i] among all rotations of a given array in C++
- Find Maximum value of abs(i – j) * min(arr[i], arr[j]) in an array arr[] in C++
- Count of unique pairs (arr[i], arr[j]) such that i < j in C++
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i] in C++
- Count pairs in an array such that LCM(arr[i], arr[j]) > min(arr[i],arr[j]) in C++
- Sum of the elements from index L to R in an array when arr[i] = i * (-1)^i in C++
- Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]
- Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed in C++
- Count pairs in an array that hold i*arr[i] > j*arr[j] in C++
- Maximum modulo of all the pairs of array where arr[i] >= arr[j] in C++

Advertisements