Input: arr[] = [4, 3, 2, 6, 1, 5]
Output: 60
Explanation: After rotating the array 3 times, we get [1, 5, 4, 3, 2, 6]. Now, the sum of i*arr[i] = 0*1 + 1*5 + 2*4 + 3*3 + 4*2 + 5*6 = 0 + 5 + 8 + 9 + 8 + 30 = 60
Input: arr[] = [8, 3, 1, 2]
Output: 29
Explanation: After rotating the array 3 times, we get [3, 1, 2, 8]. Now, the sum of i*arr[i] = 0*3 + 1*1 + 2*2 + 3*8 = 0 + 1 + 4 + 24 = 29.
Input: arr[] = [10, 1, 2, 7, 9, 3]
Output: 105
The idea is to check all possible rotations of the array. As on each rotation, the value of the expression changes as the index positions shift. We rotate the array one step at a time and compute the new sum. By tracking the maximum of these sum values, we ensure we capture the best possible configuration.
The idea is to compute the sum of i*arr[i] for each possible rotation without recalculating it from scratch each time. Instead, we calculate the next rotation value from the previous rotation, i.e., calculate Rj from Rj-1. So, we can calculate the initial value of the result as R0, then keep calculating the next rotation values.
Let us calculate initial value of i*arr[i] with no rotation
R0 = 0*arr[0] + 1*arr[1] +...+ (n-1)*arr[n-1]
After 1 rotation arr[n-1], becomes first element of array,
- arr[0] becomes second element, arr[1] becomes third element and so on.
- R1 = 0*arr[n-1] + 1*arr[0] +...+ (n-1)*arr[n-2]
- R1 - R0 = arr[0] + arr[1] + ... + arr[n-2] - (n-1)*arr[n-1]
After 2 rotations arr[n-2], becomes first element of array,
- arr[n-1] becomes second element, arr[0] becomes third element and so on.
- R2 = 0*arr[n-2] + 1*arr[n-1] +...+ (n-1)*arr[n-3]
- R2 - R1 = arr[0] + arr[1] + ... + arr[n-3] - (n-1)*arr[n-2] + arr[n-1]
If we take a closer look at above values, we can observe below pattern:
Rj - Rj-1 = totalSum - n * arr[n-j]
Where totalSum is sum of all array elements
Given arr[]={10, 1, 2, 3, 4, 5, 6, 7, 8, 9}, |
arrSum = 55, currVal = summation of (i*arr[i]) = 285
In each iteration the currVal is currVal = currVal + arrSum-n*arr[n-j] ,
1st rotation: currVal = 285 + 55 - (10 * 9) = 250
2nd rotation: currVal = 250 + 55 - (10 * 8) = 225
3rd rotation: currVal = 225 + 55 - (10 * 7) = 210
.......
Last rotation: currVal = 285 + 55 - (10 * 1) = 330
Previous currVal was 285, now it becomes 330.
It's the maximum value we can find hence return 330.