C++ Program to Maximum sum of i*arr[i] among all rotations of a given array
Last Updated :
25 May, 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++
// A Naive C++ program to find maximum sum rotation
#include<bits/stdc++.h>
using namespace std;
// Returns maximum value of i*arr[i]
int maxSum(int arr[], int n)
{
// Initialize result
int res = INT_MIN;
// Consider rotation beginning with i
// for all possible values of i.
for (int i=0; i<n; i++)
{
// Initialize sum of current rotation
int curr_sum = 0;
// Compute sum of all values. We don't
// actually rotate the array, instead of that we compute the
// sum by finding indexes when arr[i] is
// first element
for (int j=0; j<n; j++)
{
int index = (i+j)%n;
curr_sum += j*arr[index];
}
// Update result if required
res = max(res, curr_sum);
}
return res;
}
// Driver code
int main()
{
int arr[] = {8, 3, 1, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n) << endl;
return 0;
}
Output :
29
- Complexity Analysis:
Time Complexity : O(n2), as we are using nested loops.
Auxiliary Space : O(1), as we are not using any extra space.
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
C++
// An efficient C++ program to compute
// maximum sum of i*arr[i]
#include<bits/stdc++.h>
using namespace std;
int maxSum(int arr[], int n)
{
// Compute sum of all array elements
int cum_sum = 0;
for (int i=0; i<n; i++)
cum_sum += arr[i];
// Compute sum of i*arr[i] for initial
// configuration.
int curr_val = 0;
for (int i=0; i<n; i++)
curr_val += i*arr[i];
// Initialize result
int res = curr_val;
// Compute values for other iterations
for (int i=1; i<n; i++)
{
// Compute next value using previous
// value in O(1) time
int 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
int main()
{
int arr[] = {8, 3, 1, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n) << endl;
return 0;
}
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)
- 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:
- 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)
Similar Reads
C++ Program to Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possible summation of i*arr[i]. 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 I
4 min read
C++ Program to 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:
3 min read
C++ Program to Modify given array to a non-decreasing array by rotation Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation:Â After
2 min read
C++ Program for Queries to find maximum sum contiguous subarrays of given length in a rotating array Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types: If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array. Examples:Â Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2,
5 min read
C++ Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0;
6 min read
C++ Program to Maximize count of corresponding same elements in given Arrays by Rotation Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples:  Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3,
3 min read
C++ Program to Find Maximum value possible by rotating digits of a given number Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N. Examples: Input: N = 657Output: 765Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765. Input: N = 7092Output: 9270Explanati
2 min read
C++ Program to Count of rotations required to generate a sorted array Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples: Input: arr[] = {4, 5, 1, 2, 3}Â Output: 2Â Explanation:Â Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations. Input: arr[] = {2, 1, 2, 2, 2}Â Output: 1Â Explanation:Â So
4 min read
C++ Program for Maximum equilibrium sum in an array Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[]. Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1} Output : 4 Prefix sum of arr[0..3] = Suffix sum of arr[3..6] Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2} Output : 7 Prefix sum of arr[0..3] = Su
4 min read
Modify given array to a non-decreasing array by rotation Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation: After
10 min read