Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1.
Examples:
Input: arr[] = {8, 3, 1, 2}
Output: 29
Explanation: Lets look at all the rotations,
{8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11
{3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29
{1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27
{2, 8, 3, 1} = 2*0 + 8*1 + 3*2 + 1*1 = 17
Input: arr[] = {3, 2, 1}
Output: 7
Explanation: Lets look at all the rotations,
{3, 2, 1} = 3*0 + 2*1 + 1*2 = 4
{2, 1, 3} = 2*0 + 1*1 + 3*2 = 7
{1, 3, 2} = 1*0 + 3*1 + 2*2 = 7
Method 1: This method discusses the Naive Solution which takes O(n2) amount of time.
The solution involves finding the sum of all the elements of the array in each rotation and then deciding the maximum summation value.
- Approach:A simple solution is to try all possible rotations. Compute sum of i*arr[i] for every rotation and return maximum sum.
- Algorithm:
- Rotate the array for all values from 0 to n.
- Caluclate the sum for each rotations.
- Check if the maximum sum is greater than the current sum then update the maximum sum.
-
Implementation:
C++
// A Naive C++ program to find maximum sum rotation#include<bits/stdc++.h>usingnamespacestd;// Returns maximum value of i*arr[i]intmaxSum(intarr[],intn){// Initialize resultintres = INT_MIN;// Consider rotation beginning with i// for all possible values of i.for(inti=0; i<n; i++){// Initialize sum of current rotationintcurr_sum = 0;// Compute sum of all values. We don't// acutally rotation the array, but compute// sum by finding ndexes when arr[i] is// first elementfor(intj=0; j<n; j++){intindex = (i+j)%n;curr_sum += j*arr[index];}// Update result if requiredres = max(res, curr_sum);}returnres;}// Driver codeintmain(){intarr[] = {8, 3, 1, 2};intn =sizeof(arr)/sizeof(arr[0]);cout << maxSum(arr, n) << endl;return0;}chevron_rightfilter_noneJava
// A Naive Java program to find// maximum sum rotationimportjava.util.*;importjava.io.*;classGFG {// Returns maximum value of i*arr[i]staticintmaxSum(intarr[],intn){// Initialize resultintres = Integer.MIN_VALUE;// Consider rotation beginning with i// for all possible values of i.for(inti =0; i < n; i++){// Initialize sum of current rotationintcurr_sum =0;// Compute sum of all values. We don't// actually rotation the array, but compute// sum by finding ndexes when arr[i] is// first elementfor(intj =0; j < n; j++){intindex = (i + j) % n;curr_sum += j * arr[index];}// Update result if requiredres = Math.max(res, curr_sum);}returnres;}// Driver codepublicstaticvoidmain(String args[]){intarr[] = {8,3,1,2};intn = arr.length;System.out.println(maxSum(arr, n));}}// This code is contributed by Sahil_Bansallchevron_rightfilter_nonePython3
# A Naive Python 3 program to find# maximum sum rotationimportsys# Returns maximum value of i * arr[i]defmaxSum(arr, n):# Initialize resultres=-sys.maxsize# Consider rotation beginning with i# for all possible values of i.foriinrange(0, n):# Initialize sum of current rotationcurr_sum=0# Compute sum of all values. We don't# acutally rotation the array, but# compute sum by finding ndexes when# arr[i] is first elementforjinrange(0, n):index=int((i+j)%n)curr_sum+=j*arr[index]# Update result if requiredres=max(res, curr_sum)returnres# Driver codearr=[8,3,1,2]n=len(arr)print(maxSum(arr, n))# This code is contributed by# Smitha Dinesh Semwalchevron_rightfilter_noneC#
// A Naive C# program to find// maximum sum rotationusingSystem;classGFG {// Returns maximum value of i*arr[i]staticintmaxSum(int[] arr,intn){// Initialize resultintres =int.MinValue;// Consider rotation beginning with i// for all possible values of i.for(inti = 0; i < n; i++) {// Initialize sum of current rotationintcurr_sum = 0;// Compute sum of all values. We don't// acutally rotation the array, but compute// sum by finding ndexes when arr[i] is// first elementfor(intj = 0; j < n; j++){intindex = (i + j) % n;curr_sum += j * arr[index];}// Update result if requiredres = Math.Max(res, curr_sum);}returnres;}// Driver codepublicstaticvoidMain(){int[] arr = { 8, 3, 1, 2 };intn = arr.Length;Console.WriteLine(maxSum(arr, n));}}// This code is contributed by vt_m.chevron_rightfilter_nonePHP
<?php// A Naive PHP program to// find maximum sum rotation// Returns maximum value// of i*arr[i]functionmaxSum($arr,$n){// Initialize result$res= PHP_INT_MIN;// Consider rotation beginning// with i for all possible// values of i.for($i= 0;$i<$n;$i++){// Initialize sum of// current rotation$curr_sum= 0;// Compute sum of all values.// We don't actually rotate// the array, but compute sum// by finding indexes when// arr[i] is first elementfor($j= 0;$j<$n;$j++){$index= ($i+$j) %$n;$curr_sum+=$j*$arr[$index];}// Update result if required$res= max($res,$curr_sum);}return$res;}// Driver code$arr=array(8, 3, 1, 2);$n= sizeof($arr);echomaxSum($arr,$n),"\n";// This code is contributed by ajit?>chevron_rightfilter_none- Output :
29
- Complexity Analysis:
- Time Complexity : O(n2)
- Auxiliary Space : O(1)
Method 2: This method discusses the efficient solution which solves the problem in O(n) time. In the naive solution, the values were calculated for every rotation. So if that can be done in constant time then the complexity will decrease.
- Approach: The basic approach is to calculate the sum of new rotation from the previous rotations. This brings up a similarity where only the multipliers of first and last element change drastically and the multiplier of every other element increases or decreases by 1. So in this way, the sum of next rotation can be calculated from the sum of present rotation.
- Algorithm:
The idea is to compute the value of a rotation using values of previous rotation. When an array is rotated by one, following changes happen in sum of i*arr[i].- Multiplier of arr[i-1] changes from 0 to n-1, i.e., arr[i-1] * (n-1) is added to current value.
- Multipliers of other terms is decremented by 1. i.e., (cum_sum – arr[i-1]) is subtracted from current value where cum_sum is sum of all numbers.
next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1); next_val = Value of ∑i*arr[i] after one rotation. curr_val = Current value of ∑i*arr[i] cum_sum = Sum of all array elements, i.e., ∑arr[i]. Lets take example {1, 2, 3}. Current value is 1*0+2*1+3*2 = 8. Shifting it by one will make it {2, 3, 1} and next value will be 8 - (6 - 1) + 1*2 = 5 which is same as 2*0 + 3*1 + 1*2 - Implementation:
C++
// An efficient C++ program to compute// maximum sum of i*arr[i]#include<bits/stdc++.h>usingnamespacestd;intmaxSum(intarr[],intn){// Compute sum of all array elementsintcum_sum = 0;for(inti=0; i<n; i++)cum_sum += arr[i];// Compute sum of i*arr[i] for initial// configuration.intcurr_val = 0;for(inti=0; i<n; i++)curr_val += i*arr[i];// Initialize resultintres = curr_val;// Compute values for other iterationsfor(inti=1; i<n; i++){// Compute next value using previous// value in O(1) timeintnext_val = curr_val - (cum_sum - arr[i-1])+ arr[i-1] * (n-1);// Update current valuecurr_val = next_val;// Update result if requiredres = max(res, next_val);}returnres;}// Driver codeintmain(){intarr[] = {8, 3, 1, 2};intn =sizeof(arr)/sizeof(arr[0]);cout << maxSum(arr, n) << endl;return0;}chevron_rightfilter_noneJava
// An efficient Java program to compute// maximum sum of i*arr[i]importjava.io.*;classGFG {staticintmaxSum(intarr[],intn){// Compute sum of all array elementsintcum_sum =0;for(inti =0; i < n; i++)cum_sum += arr[i];// Compute sum of i*arr[i] for// initial configuration.intcurr_val =0;for(inti =0; i < n; i++)curr_val += i * arr[i];// Initialize resultintres = curr_val;// Compute values for other iterationsfor(inti =1; i < n; i++){// Compute next value using previous// value in O(1) timeintnext_val = curr_val - (cum_sum -arr[i-1]) + arr[i-1] *(n-1);// Update current valuecurr_val = next_val;// Update result if requiredres = Math.max(res, next_val);}returnres;}// Driver codepublicstaticvoidmain(String[] args){intarr[] = {8,3,1,2};intn = arr.length;System.out.println(maxSum(arr, n));}}// This code is contributed by Prerna Sainichevron_rightfilter_nonePython3
# An efficient Python 3 program to# compute maximum sum of i * arr[i]defmaxSum(arr, n):# Compute sum of all array elementscum_sum=0foriinrange(0, n):cum_sum+=arr[i]# Compute sum of i * arr[i] for# initial configuration.curr_val=0foriinrange(0, n):curr_val+=i*arr[i]# Initialize resultres=curr_val# Compute values for other iterationsforiinrange(1, n):# Compute next value using previous# value in O(1) timenext_val=(curr_val-(cum_sum-arr[i-1])+arr[i-1]*(n-1))# Update current valuecurr_val=next_val# Update result if requiredres=max(res, next_val)returnres# Driver codearr=[8,3,1,2]n=len(arr)print(maxSum(arr, n))# This code is contributed by# Smitha Dinesh Semwalchevron_rightfilter_noneC#
// An efficient C# program to compute// maximum sum of i*arr[i]usingSystem;classGFG {staticintmaxSum(int[]arr,intn){// Compute sum of all array elementsintcum_sum = 0;for(inti = 0; i < n; i++)cum_sum += arr[i];// Compute sum of i*arr[i] for// initial configuration.intcurr_val = 0;for(inti = 0; i < n; i++)curr_val += i * arr[i];// Initialize resultintres = curr_val;// Compute values for other iterationsfor(inti = 1; i < n; i++){// Compute next value using previous// value in O(1) timeintnext_val = curr_val - (cum_sum -arr[i - 1]) + arr[i - 1] *(n - 1);// Update current valuecurr_val = next_val;// Update result if requiredres = Math.Max(res, next_val);}returnres;}// Driver codepublicstaticvoidMain(){int[]arr = {8, 3, 1, 2};intn = arr.Length;Console.Write(maxSum(arr, n));}}// This code is contributed by nitin mittalchevron_rightfilter_nonePHP
<?php// An efficient PHP program to// compute maximum sum of i*arr[i]functionmaxSum($arr,$n){// Compute sum of all// array elements$cum_sum= 0;for($i= 0;$i<$n;$i++)$cum_sum+=$arr[$i];// Compute sum of i*arr[i]// for initial configuration.$curr_val= 0;for($i= 0;$i<$n;$i++)$curr_val+=$i*$arr[$i];// Initialize result$res=$curr_val;// Compute values for// other iterationsfor($i= 1;$i<$n;$i++){// Compute next value using// previous value in O(1) time$next_val=$curr_val-($cum_sum-$arr[$i- 1]) +$arr[$i- 1] * ($n- 1);// Update current value$curr_val=$next_val;// Update result if required$res= max($res,$next_val);}return$res;}// Driver code$arr=array(8, 3, 1, 2);$n= sizeof($arr);echomaxSum($arr,$n);// This code is contributed by ajit?>chevron_rightfilter_none - Output:
29
- Complexity analysis:
- Time Complexity: O(n).
Since one loop is needed from 0 to n to check all rotations and the sum of the present rotation is calculated from the previous rotations in O(1) time). - Auxiliary Space: O(1).
As no extra space is required to so the space complexity will be O(1)
- Time Complexity: O(n).
Method 3: The method discusses the solution using pivot in O(n) time. The pivot method can only be used in the case of a sorted or a rotated sorted array. For example: {1, 2, 3, 4} or {2, 3, 4, 1}, {3, 4, 1, 2} etc.
- Approach: Let’s assume the case of a sorted array. As we know for an array the maximum sum will be when the array is sorted in ascending order. In case of a sorted rotated array, we can rotate the array to make it in ascending order. So, in this case, the pivot element is needed to be found following which the maximum sum can be calculated.
- Algorithm:
- Find the pivot of the array: if arr[i] > arr[(i+1)%n] then it is the pivot element. (i+1)%n is used to check for the last and first element.
- After getting pivot the sum can be calculated by finding the difference with the pivot which will be the multiplier and multiply it with the current element while calculating the sum
- Implementations:
C++
// C++ program to find maximum sum of all// rotation of i*arr[i] using pivot.#include <iostream>usingnamespacestd;// fun declarationintmaxSum(intarr[],intn);intfindPivot(intarr[],intn);// function definitionintmaxSum(intarr[],intn){intsum = 0;inti;intpivot = findPivot(arr, n);// difference in pivot and index of// last element of arrayintdiff = n - 1 - pivot;for(i = 0; i < n; i++){sum = sum + ((i + diff) % n) * arr[i];}returnsum;}// function to find pivotintfindPivot(intarr[],intn){inti;for(i = 0; i < n; i++){if(arr[i] > arr[(i + 1) % n])returni;}}// Driver codeintmain(void){// rotated input arrayintarr[] = {8, 3, 1, 2};intn =sizeof(arr) /sizeof(int);intmax = maxSum(arr, n);cout << max;return0;}// This code is contributed by Shubhamsingh10chevron_rightfilter_noneC
// C program to find maximum sum of all// rotation of i*arr[i] using pivot.#include<stdio.h>// fun declarationintmaxSum(intarr[],intn);intfindPivot(intarr[],intn);// function definitionintmaxSum(intarr[],intn){intsum = 0;inti;intpivot = findPivot(arr, n);// difference in pivot and index of// last element of arrayintdiff = n - 1 - pivot;for(i = 0; i < n; i++){sum= sum + ((i + diff) % n) * arr[i];}returnsum;}// function to find pivotintfindPivot(intarr[],intn){inti;for(i = 0; i < n; i++){if(arr[i] > arr[(i + 1) % n])returni;}}// Driver codeintmain(void){// rotated input arrayintarr[] = {8, 3, 1, 2};intn =sizeof(arr) /sizeof(int);intmax = maxSum(arr, n);printf("%d", max);return0;}chevron_rightfilter_noneJava
// Java program to find maximum sum// of all rotation of i*arr[i] using pivot.importjava.util.*;importjava.lang.*;importjava.io.*;classGFG{// function definitionstaticintmaxSum(intarr[],intn){intsum =0;inti;intpivot = findPivot(arr, n);// difference in pivot and index of// last element of arrayintdiff = n -1- pivot;for(i =0; i < n; i++){sum= sum + ((i + diff) % n) * arr[i];}returnsum;}// function to find pivotstaticintfindPivot(intarr[],intn){inti;for(i =0; i < n; i++){if(arr[i] > arr[(i +1) % n])returni;}return0;}// Driver codepublicstaticvoidmain(String args[]){// rotated input arrayintarr[] = {8,3,1,2};intn = arr.length;intmax = maxSum(arr,n);System.out.println(max);}}chevron_rightfilter_nonePython3
# Python3 program to find maximum sum of# all rotation of i*arr[i] using pivot.# function definitiondefmaxSum(arr, n) :sum=0pivot=findPivot(arr, n)# difference in pivot and index# of last element of arraydiff=n-1-pivotforiinrange(n) :sum=sum+((i+diff)%n)*arr[i];returnsum# function to find pivotdeffindPivot(arr, n) :foriinrange(n) :if(arr[i] > arr[(i+1)%n]) :returni;# Driver codeif__name__=="__main__":# rotated input arrayarr=[8,3,1,2]n=len(arr)max=maxSum(arr, n)print(max)# This code is contributed by Ryugachevron_rightfilter_noneC#
// C# program to find maximum sum// of all rotation of i*arr[i] using pivot.usingSystem;classGFG{// function definitionpublicstaticintmaxSum(int[] arr,intn){intsum = 0;inti;intpivot = findPivot(arr,n);// difference in pivot and index of// last element of arrayintdiff = n - 1 - pivot;for(i = 0;i < n;i++){sum = sum + ((i + diff) % n) * arr[i];}returnsum;}// function to find pivotpublicstaticintfindPivot(int[] arr,intn){inti;for(i = 0; i < n; i++){if(arr[i] > arr[(i + 1) % n]){returni;}}return0;}// Driver codepublicstaticvoidMain(string[] args){// rotated input arrayint[] arr =newint[] {8, 3, 1, 2};intn = arr.Length;intmax = maxSum(arr,n);Console.WriteLine(max);}}// This code is contributed by Shrikant13chevron_rightfilter_nonePHP
<?php// PHP program to find maximum sum// of all rotation of i*arr[i] using pivot.// function definitionfunctionmaxSum($arr,$n){$sum= 0;$pivot= findPivot($arr,$n);// difference in pivot and index of// last element of array$diff=$n- 1 -$pivot;for($i= 0;$i<$n;$i++){$sum=$sum+ (($i+$diff) %$n) *$arr[$i];}return$sum;}// function to find pivotfunctionfindPivot($arr,$n){for($i= 0;$i<$n;$i++){if($arr[$i] >$arr[($i+ 1) %$n])return$i;}return0;}// Driver code// rotated input array$arr=array(8, 3, 1, 2);$n= sizeof($arr);$max= maxSum($arr,$n);echo$max;// This code is contributed// by Akanksha Rai(Abby_akku)?>chevron_rightfilter_none - Output:
29
- Complexity analysis:
- Time Complexity : O(n)
As only one loop was needed to traverse from 0 to n to find the pivot. To find the sum another loop was needed, so the complexity remains O(n). - Auxiliary Space : O(1).
We do not require extra space to so the Auxiliary space is O(1)
- Time Complexity : O(n)
This article is contributed by Shubham Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Maximum XOR value of maximum and second maximum element among all possible subarrays
- Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
- Maximum LCM among all pairs (i, j) from the given Array
- Check whether all the rotations of a given number is greater than or equal to the given number or not
- Print all possible rotations of a given Array
- Maximum sum of values of nodes among all connected components of an undirected graph
- Maximum value of XOR among all triplets of an array
- Generate two BSTs from the given array such that maximum height among them is minimum
- Range sum queries for anticlockwise rotations of Array by K indices
- Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings
- Maximum contiguous 1 possible in a binary string after k rotations
- Check if all rows of a matrix are circular rotations of each other
- Generate all rotations of a number
- Sum of bit differences among all pairs
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Pair of integers having least GCD among all given pairs having GCD exceeding K
- Find element at given index after a number of rotations
- Maximize count of corresponding same elements in given permutations using cyclic rotations
- Quickly find multiple left rotations of an array | Set 1
- Count of rotations required to generate a sorted array

