Maximum sum of i * arr [ i ] among all rotations of a given array | An efficient JavaScript program to compute maximum sum of i * arr [ i ] ; Compute sum of all array elements ; Compute sum of i * arr [ i ] for initial configuration . ; Initialize result ; Compute values for other iterations ; Compute next value using previous value in O ( 1 ) time ; Update current value ; Update result if required ; Driver code
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 ) + " " ) ;