Find the maximum possible value of last element of the Array | Function to find the maximum possible value of last element of the array ; Traverse for all element ; Find the distance ; If moves less than distance then we can not move this number to end ; How many number we can move to end ; Take the minimum of both of them ; Increment in the end ; Remove taken moves ; Return the last element ; Driver code ; Function call
function maxValue ( arr , n , moves ) { for ( var i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { var distance = n - 1 - i ; if ( moves < distance ) break ; var can_take = parseInt ( moves / distance ) ; var take = Math . min ( arr [ i ] , can_take ) ; arr [ n - 1 ] += take ; moves -= take * distance ; } } return arr [ n - 1 ] ; } var arr = [ 2 , 3 , 0 , 1 ] ; var M = 5 ; var N = arr . length ; document . write ( maxValue ( arr , N , M ) ) ;