Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Program to Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
In JavaScript, we need to find the maximum value of Sum(i*arr[i]) by rotating an array. This problem can be solved efficiently using a mathematical approach that avoids checking all possible rotations.
Problem Understanding
Given an array, we can rotate it left or right. For each rotation, we calculate the sum of (index × element). Our goal is to find the maximum possible sum across all rotations.
For example, with array [1, 20, 2, 10]:
- Original: (0×1) + (1×20) + (2×2) + (3×10) = 54
- Rotate 1: (0×20) + (1×2) + (2×10) + (3×1) = 25
- Rotate 2: (0×2) + (1×10) + (2×1) + (3×20) = 72 (maximum)
Mathematical Approach
Instead of generating all rotations, we use the mathematical relationship between consecutive rotations. When we rotate left by one position, the new sum can be calculated using the previous sum.
function maxSum(arr) {
let n = arr.length;
let arrSum = 0;
let currVal = 0;
// Calculate sum of array and initial sum of i*arr[i]
for (let i = 0; i
Array: [1, 20, 2, 10]
Maximum sum: 72
Array: [8, 3, 1, 2]
Maximum sum: 29
How It Works
The algorithm works in two phases:
-
Initial Calculation: Calculate the sum of all elements (arrSum) and the sum of i*arr[i] for the original array (currVal)
-
Rotation Formula: For each subsequent rotation, use the formula:
newSum = prevSum + arrSum - n * arr[n-j]
The mathematical insight is that when we rotate left, each element moves to a higher index (contributing more to the sum), except the last element which moves to index 0.
Step-by-Step Example
function maxSumWithSteps(arr) {
let n = arr.length;
let arrSum = 0;
let currVal = 0;
console.log("Original array:", arr);
// Calculate initial values
for (let i = 0; i
Original array: [1, 20, 2, 10]
Array sum: 33
Initial sum (i*arr[i]): 54
Rotation 1: sum = 25
Rotation 2: sum = 72
Rotation 3: sum = 47
Maximum sum: 72
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time | O(n) | Two separate loops of n iterations |
| Space | O(1) | Only constant extra variables used |
Conclusion
This mathematical approach efficiently finds the maximum sum of i*arr[i] across all rotations in O(n) time. The key insight is using the relationship between consecutive rotations rather than calculating each rotation from scratch.
