Javascript Program for 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:
JavaScript
<script>
// A Naive javascript program to find
// maximum sum rotation // Returns maximum value of i*arr[i]
function maxSum(arr , n) {
// Initialize result
var res = Number.MIN_VALUE;
// Consider rotation beginning with i
// for all possible values of i.
for (i = 0; i < n; i++) {
// Initialize sum of current rotation
var curr_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 element
for (j = 0; j < n; j++) {
var index = (i + j) % n;
curr_sum += j * arr[index];
}
// Update result if required
res = Math.max(res, curr_sum);
}
return res;
}
// Driver code
var arr = [ 8, 3, 1, 2 ];
var n = arr.length;
document.write(maxSum(arr, n));
// This code contributed by umadevi9616
</script>
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
JavaScript
<script>
// An efficient JavaScript program to compute
// maximum sum of i*arr[i]
function maxSum(arr, n)
{
// Compute sum of all array elements
let cum_sum = 0;
for (let i=0; i<n; i++)
cum_sum += arr[i];
// Compute sum of i*arr[i] for initial
// configuration.
let curr_val = 0;
for (let i=0; i<n; i++)
curr_val += i*arr[i];
// Initialize result
let res = curr_val;
// Compute values for other iterations
for (let i=1; i<n; i++)
{
// Compute next value using previous
// value in O(1) time
let 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 = Math.max(res, next_val);
}
return res;
}
// Driver code
let arr = [8, 3, 1, 2];
let n = arr.length;
document.write(maxSum(arr, n) + "<br>");
// This code is contributed by Surbhi Tyagi.
</script>
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)
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:
JavaScript
<script>
// js program to find maximum sum
// of all rotation of i*arr[i] using pivot.
// function definition
function maxSum(arr, n)
{
let sum = 0;
let i;
let pivot = findPivot(arr,n);
// difference in pivot and index of
// last element of array
let diff = n - 1 - pivot;
for (i = 0;i < n;i++)
{
sum = sum + ((i + diff) % n) * arr[i];
}
return sum;
}
// function to find pivot
function findPivot(arr, n)
{
let i;
for (i = 0; i < n; i++)
{
if (arr[i] > arr[(i + 1) % n])
{
return i;
}
}
return 0;
}
// Driver code
// rotated input array
let arr = [8, 3, 1, 2];
let n = arr.length;
let ma = maxSum(arr,n);
document.write(ma);
// This code is contributed by mohit kumar 29.
</script>
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)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read