Maximum sum of i*arr[i] among all rotations of a given array
Last Updated :
14 Dec, 2022
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*3 = 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.
- Calculate the sum for each rotations.
- Check if the maximum sum is greater than the current sum then update the maximum sum.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int maxSum(int arr[], int n)
{
int res = INT_MIN;
for (int i=0; i<n; i++)
{
int curr_sum = 0;
for (int j=0; j<n; j++)
{
int index = (i+j)%n;
curr_sum += j*arr[index];
}
res = max(res, curr_sum);
}
return res;
}
int main()
{
int arr[] = {8, 3, 1, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n) << endl;
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
static int maxSum(int arr[], int n)
{
int res = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
int curr_sum = 0;
for (int j = 0; j < n; j++)
{
int index = (i + j) % n;
curr_sum += j * arr[index];
}
res = Math.max(res, curr_sum);
}
return res;
}
public static void main(String args[])
{
int arr[] = {8, 3, 1, 2};
int n = arr.length;
System.out.println(maxSum(arr, n));
}
}
|
Python3
import sys
def maxSum(arr, n):
res = -sys.maxsize
for i in range(0, n):
curr_sum = 0
for j in range(0, n):
index = int((i + j)% n)
curr_sum += j * arr[index]
res = max(res, curr_sum)
return res
arr = [8, 3, 1, 2]
n = len(arr)
print(maxSum(arr, n))
|
C#
using System;
class GFG {
static int maxSum(int[] arr, int n)
{
int res = int.MinValue;
for (int i = 0; i < n; i++) {
int curr_sum = 0;
for (int j = 0; j < n; j++)
{
int index = (i + j) % n;
curr_sum += j * arr[index];
}
res = Math.Max(res, curr_sum);
}
return res;
}
public static void Main()
{
int[] arr = { 8, 3, 1, 2 };
int n = arr.Length;
Console.WriteLine(maxSum(arr, n));
}
}
|
PHP
<?php
function maxSum($arr, $n)
{
$res = PHP_INT_MIN;
for ($i = 0; $i < $n; $i++)
{
$curr_sum = 0;
for ($j = 0; $j < $n; $j++)
{
$index = ($i + $j) % $n;
$curr_sum += $j * $arr[$index];
}
$res = max($res, $curr_sum);
}
return $res;
}
$arr = array(8, 3, 1, 2);
$n = sizeof($arr);
echo maxSum($arr, $n), "\n";
?>
|
Javascript
<script>
function maxSum(arr , n) {
var res = Number.MIN_VALUE;
for (i = 0; i < n; i++) {
var curr_sum = 0;
for (j = 0; j < n; j++) {
var index = (i + j) % n;
curr_sum += j * arr[index];
}
res = Math.max(res, curr_sum);
}
return res;
}
var arr = [ 8, 3, 1, 2 ];
var n = arr.length;
document.write(maxSum(arr, n));
</script>
|
- 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++
#include<bits/stdc++.h>
using namespace std;
int maxSum(int arr[], int n)
{
int cum_sum = 0;
for (int i=0; i<n; i++)
cum_sum += arr[i];
int curr_val = 0;
for (int i=0; i<n; i++)
curr_val += i*arr[i];
int res = curr_val;
for (int i=1; i<n; i++)
{
int next_val = curr_val - (cum_sum - arr[i-1])
+ arr[i-1] * (n-1);
curr_val = next_val;
res = max(res, next_val);
}
return res;
}
int main()
{
int arr[] = {8, 3, 1, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int maxSum(int arr[], int n)
{
int cum_sum = 0;
for (int i = 0; i < n; i++)
cum_sum += arr[i];
int curr_val = 0;
for (int i = 0; i < n; i++)
curr_val += i * arr[i];
int res = curr_val;
for (int i = 1; i < n; i++)
{
int next_val = curr_val - (cum_sum -
arr[i-1]) + arr[i-1] *
(n-1);
curr_val = next_val;
res = Math.max(res, next_val);
}
return res;
}
public static void main(String[] args)
{
int arr[] = {8, 3, 1, 2};
int n = arr.length;
System.out.println(maxSum(arr, n));
}
}
|
Python3
def maxSum(arr, n):
cum_sum = 0
for i in range(0, n):
cum_sum += arr[i]
curr_val = 0
for i in range(0, n):
curr_val += i * arr[i]
res = curr_val
for i in range(1, n):
next_val = (curr_val - (cum_sum - arr[i-1]) +
arr[i-1] * (n-1))
curr_val = next_val
res = max(res, next_val)
return res
arr = [8, 3, 1, 2]
n = len(arr)
print(maxSum(arr, n))
|
C#
using System;
class GFG {
static int maxSum(int []arr, int n)
{
int cum_sum = 0;
for (int i = 0; i < n; i++)
cum_sum += arr[i];
int curr_val = 0;
for (int i = 0; i < n; i++)
curr_val += i * arr[i];
int res = curr_val;
for (int i = 1; i < n; i++)
{
int next_val = curr_val - (cum_sum -
arr[i - 1]) + arr[i - 1] *
(n - 1);
curr_val = next_val;
res = Math.Max(res, next_val);
}
return res;
}
public static void Main()
{
int []arr = {8, 3, 1, 2};
int n = arr.Length;
Console.Write(maxSum(arr, n));
}
}
|
PHP
<?php
function maxSum($arr, $n)
{
$cum_sum = 0;
for ($i = 0; $i < $n; $i++)
$cum_sum += $arr[$i];
$curr_val = 0;
for ($i = 0; $i < $n; $i++)
$curr_val += $i * $arr[$i];
$res = $curr_val;
for ($i = 1; $i < $n; $i++)
{
$next_val = $curr_val -
($cum_sum - $arr[$i - 1]) +
$arr[$i - 1] * ($n - 1);
$curr_val = $next_val;
$res = max($res, $next_val);
}
return $res;
}
$arr = array(8, 3, 1, 2);
$n = sizeof($arr);
echo maxSum($arr, $n);
?>
|
Javascript
<script>
function maxSum(arr, n)
{
let cum_sum = 0;
for (let i=0; i<n; i++)
cum_sum += arr[i];
let curr_val = 0;
for (let i=0; i<n; i++)
curr_val += i*arr[i];
let res = curr_val;
for (let i=1; i<n; i++)
{
let next_val = curr_val - (cum_sum - arr[i-1])
+ arr[i-1] * (n-1);
curr_val = next_val;
res = Math.max(res, next_val);
}
return res;
}
let arr = [8, 3, 1, 2];
let n = arr.length;
document.write(maxSum(arr, n) + "<br>");
</script>
|
- 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)
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++
#include <iostream>
using namespace std;
int maxSum(int arr[], int n);
int findPivot(int arr[], int n);
int maxSum(int arr[], int n)
{
int sum = 0;
int i;
int pivot = findPivot(arr, n);
int diff = n - 1 - pivot;
for(i = 0; i < n; i++)
{
sum = sum + ((i + diff) % n) * arr[i];
}
return sum;
}
int findPivot(int arr[], int n)
{
int i;
for(i = 0; i < n; i++)
{
if(arr[i] > arr[(i + 1) % n])
return i;
}
}
int main(void)
{
int arr[] = {8, 13, 1, 2};
int n = sizeof(arr) / sizeof(int);
int max = maxSum(arr, n);
cout << max;
return 0;
}
|
C
#include<stdio.h>
int maxSum(int arr[], int n);
int findPivot(int arr[], int n);
int maxSum(int arr[], int n)
{
int sum = 0;
int i;
int pivot = findPivot(arr, n);
int diff = n - 1 - pivot;
for(i = 0; i < n; i++)
{
sum= sum + ((i + diff) % n) * arr[i];
}
return sum;
}
int findPivot(int arr[], int n)
{
int i;
for(i = 0; i < n; i++)
{
if(arr[i] > arr[(i + 1) % n])
return i;
}
}
int main(void)
{
int arr[] = {8, 13, 1, 2};
int n = sizeof(arr) / sizeof(int);
int max = maxSum(arr, n);
printf("%d", max);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int maxSum(int arr[], int n)
{
int sum = 0;
int i;
int pivot = findPivot(arr, n);
int diff = n - 1 - pivot;
for(i = 0; i < n; i++)
{
sum= sum + ((i + diff) % n) * arr[i];
}
return sum;
}
static int findPivot(int arr[], int n)
{
int i;
for(i = 0; i < n; i++)
{
if(arr[i] > arr[(i + 1) % n])
return i;
}
return 0;
}
public static void main(String args[])
{
int arr[] = {8, 13, 1, 2};
int n = arr.length;
int max = maxSum(arr,n);
System.out.println(max);
}
}
|
Python3
def maxSum(arr, n):
sum = 0
pivot = findPivot(arr, n)
diff = n - 1 - pivot
for i in range(n):
sum = sum + ((i + diff) % n) * arr[i]
return sum
def findPivot(arr, n):
for i in range(n):
if(arr[i] > arr[(i + 1) % n]):
return i
if __name__ == "__main__":
arr = [8, 13, 1, 2]
n = len(arr)
max = maxSum(arr, n)
print(max)
|
C#
using System;
class GFG
{
public static int maxSum(int[] arr, int n)
{
int sum = 0;
int i;
int pivot = findPivot(arr,n);
int diff = n - 1 - pivot;
for (i = 0;i < n;i++)
{
sum = sum + ((i + diff) % n) * arr[i];
}
return sum;
}
public static int findPivot(int[] arr, int n)
{
int i;
for (i = 0; i < n; i++)
{
if (arr[i] > arr[(i + 1) % n])
{
return i;
}
}
return 0;
}
public static void Main(string[] args)
{
int[] arr = new int[] {8, 13, 1, 2};
int n = arr.Length;
int max = maxSum(arr,n);
Console.WriteLine(max);
}
}
|
PHP
<?php
function maxSum($arr, $n)
{
$sum = 0;
$pivot = findPivot($arr, $n);
$diff = $n - 1 - $pivot;
for($i = 0; $i < $n; $i++)
{
$sum = $sum + (($i + $diff) %
$n) * $arr[$i];
}
return $sum;
}
function findPivot($arr, $n)
{
for($i = 0; $i < $n; $i++)
{
if($arr[$i] > $arr[($i + 1) % $n])
return $i;
}
return 0;
}
$arr = array(8, 13, 1, 2);
$n = sizeof($arr);
$max = maxSum($arr, $n);
echo $max;
?>
|
Javascript
<script>
function maxSum(arr, n)
{
let sum = 0;
let i;
let pivot = findPivot(arr,n);
let diff = n - 1 - pivot;
for (i = 0;i < n;i++)
{
sum = sum + ((i + diff) % n) * arr[i];
}
return sum;
}
function findPivot(arr, n)
{
let i;
for (i = 0; i < n; i++)
{
if (arr[i] > arr[(i + 1) % n])
{
return i;
}
}
return 0;
}
let arr = [8, 13, 1, 2];
let n = arr.length;
let ma = maxSum(arr,n);
document.write(ma);
</script>
|
- 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 so the Auxiliary space is O(1)
Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.
And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!
Similar Reads
Maximum sum of i*arr[i] among all rotations of a given array
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 +
15+ min read
Javascript Program for Maximum sum of i*arr[i] among all rotations of a given array
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 +
7 min read
Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
Given an array arr[] of size N, the task is to find the maximum possible sum of i*arr[i] when the array can be rotated any number of times. Examples : Input: arr[] = {1, 20, 2, 10}Output: 72.We can get 72 by rotating array twice.{2, 10, 1, 20}20*3 + 1*2 + 10*1 + 2*0 = 72 Input: arr[] = {10, 1, 2, 3,
12 min read
Maximum value of arr[i] % arr[j] for a given array
Given an array arr[], the task is to find the maximum value of arr[i] % arr[j] for all possible pairs.Examples: Input: arr[] = { 2, 3 } Output: 2 2 % 3 = 2 3 % 2 = 1 Input: arr[] = { 2, 2, 2, 2 } Output: 0 Naive Approach: Run two nested loops and calculate the value of arr[i] % arr[j] for every pair
13 min read
Maximum value of arr[i] + arr[j] + i – j for any pair of an array
Given an array arr[] consisting of N integers, the task is to find the maximum value of (arr[i] + arr[j] + i ? j) for any possible pair (i, j) of the given array. Examples: Input: arr[] = {1, 9, 3, 6, 5}Output: 13Explanation:The pair of the array having the maximum value of (arr[i] + arr[j] + i ? j)
9 min read
Maximum modulo of all the pairs of array where arr[i] >= arr[j]
Given an array of n integers. Find the maximum value of arr[i] mod arr[j] where arr[i] >= arr[j] and 1 <= i, j <= n Examples: Input: arr[] = {3, 4, 7} Output: 3 Explanation: There are 3 pairs which satisfies arr[i] >= arr[j] are:- 4, 3 => 4 % 3 = 1 7, 3 => 7 % 3 = 1 7, 4 => 7 %
8 min read
For each Array index find the maximum value among all M operations
Given an array arr[] of size N initially filled with 0 and another array Positions[] of size M, the task is to return the maximum value for each index after performing the following M operations: Make the value at index Positions[i] equal to 0All the numbers to the right of Positions[i] will be one
6 min read
Maximum OR value of a pair in an array
Given an array arr[] of N positive elements. The task is to find the maximum bitwise OR value of a pair from the given array.Examples: Input: arr[] = {4, 8, 12, 16} Output: 28 (12, 16) is the pair with the maximum bitwise OR. 12 | 16 = 28 Input: arr[] = {4, 8, 16, 2} Output: 24 Approach: Iterate ove
4 min read
Sum of maximum of all subarrays | Divide and Conquer
Given an array arr[] of length N, the task is to find the sum of the maximum elements of every possible sub-array of the array.Examples: Input : arr[] = {1, 3, 1, 7} Output : 42 Max of all sub-arrays: {1} - 1 {1, 3} - 3 {1, 3, 1} - 3 {1, 3, 1, 7} - 7 {3} - 3 {3, 1} - 3 {3, 1, 7} - 7 {1} - 1 {1, 7} -
12 min read
Print all possible rotations of a given Array
Given an integer array arr[] of size N, the task is to print all possible rotations of the array.Examples: Input: arr[] = {1, 2, 3, 4} Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} Explanation: Initial arr[] = {1, 2, 3, 4} After first rotation arr[] = {4, 1, 2, 3} After second rotat
8 min read
Find Maximum value of abs(i - j) * min(arr[i], arr[j]) in an array arr[]
Given an array of n distinct elements. Find the maximum of product of Minimum of two numbers in the array and absolute difference of their positions, i.e., find maximum value of abs(i - j) * min(arr[i], arr[j]) where i and j vary from 0 to n-1. Examples : Input : arr[] = {3, 2, 1, 4} Output: 9 // ar
7 min read
Maximize sum of diagonal of a matrix by rotating all rows or all columns
Given a square matrix, mat[][] of dimensions N * N, the task is find the maximum sum of diagonal elements possible from the given matrix by rotating either all the rows or all the columns of the matrix by a positive integer. Examples: Input: mat[][] = { { 1, 1, 2 }, { 2, 1, 2 }, { 1, 2, 2 } }Output:
8 min read
Remove all occurrences of any element for maximum array sum
Given an array of positive integers, remove all the occurrences of the element to get the maximum sum of the remaining array. Examples: Input : arr = {1, 1, 3} Output : 3 On removing 1 from the array, we get {3}. The total value is 3 Input : arr = {1, 1, 3, 3, 2, 2, 1, 1, 1} Output : 11 On removing
6 min read
Product of the maximums of all subsets of an array
Given an array arr[] consisting of N positive integers, the task is to find the product of the maximum of all possible subsets of the given array. Since the product can be very large, print it to modulo (109 + 7). Examples: Input: arr[] = {1, 2, 3}Output:Explanation:All possible subsets of the given
13 min read
Maximum element in a sorted and rotated array
Given a sorted array arr[] (may contain duplicates) of size n that is rotated at some unknown point, the task is to find the maximum element in it. Examples: Input: arr[] = {5, 6, 1, 2, 3, 4}Output: 6Explanation: 6 is the maximum element present in the array. Input: arr[] = {3, 2, 2, 2}Output: 3Expl
7 min read
Maximize sum of an Array by flipping sign of all elements of a single subarray
Given an array arr[] of N integers, the task is to find the maximum sum of the array that can be obtained by flipping signs of any subarray of the given array at most once. Examples: Input: arr[] = {-2, 3, -1, -4, -2} Output: 8Explanation: Flipping the signs of subarray {-1, -4, -2} modifies the arr
9 min read
Maximize value of (a[i]+i)*(a[j]+j) in an array
Given an array with input size n, find the maximum value of (a[i] + i) * (a[j] + j) where i is not equal to j. Note that i and j vary from 0 to n-1 . Examples: Input : a[] = [4,5,3,1,10] Output : 84 Explanation: We get the maximum value for i = 4 and j = 1 (10 + 4) * (5 + 1) = 84 Input : a[] = [10,0
12 min read
Maximum number of consecutive 1's in binary representation of all the array elements
Given an array arr[] of N elements, the task is to find the maximum number of consecutive 1's in the binary representation of an element among all the elements of the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 2 Binary(1) = 01 Binary(2) = 10 Binary(3) = 11 Binary(4) = 100 Input: arr[
6 min read
Maximum product of an Array after subtracting 1 from any element N times
Given an array arr[] of positive integers of size M and an integer N, the task is to maximize the product of array after subtracting 1 from any element N number of times Examples: Input: M = 5, arr[] = {5, 1, 7, 8, 3}, N = 2Output: 630Explanation: After subtracting 1 from arr[3] 2 times, array becom
5 min read