Maximum sum of i * arr [ i ] among all rotations of a given array | An efficient PHP 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
< ? php function maxSum ( $ arr , $ n ) { $ cum_sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ cum_sum += $ arr [ $ i ] ; $ curr_val = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ curr_val += $ i * $ arr [ $ i ] ; $ res = $ curr_val ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ next_val = $ curr_val - ( $ cum_sum - $ arr [ $ i - 1 ] ) + $ arr [ $ i - 1 ] * ( $ n - 1 ) ; $ curr_val = $ next_val ; $ res = max ( $ res , $ next_val ) ; } return $ res ; } $ arr = array ( 8 , 3 , 1 , 2 ) ; $ n = sizeof ( $ arr ) ; echo maxSum ( $ arr , $ n ) ; ? >