Maximize the rightmost element of an array in k operations in Linear Time | Function to calculate maximum value of Rightmost element ; Calculating maximum value of Rightmost element ; Checking if arr [ i ] is operationable ; Performing operation of i - th element ; Decreasing the value of k by 1 ; Printing rightmost element ; Given Input ; Function Call
function maxRightmostElement ( N , k , p , arr ) { while ( k ) { for ( let i = N - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] >= p ) { arr [ i ] = arr [ i ] - p ; arr [ i + 1 ] = arr [ i + 1 ] + p ; break ; } } k -- ; } document . write ( arr [ N - 1 ] + " " ) ; } let N = 4 , p = 2 , k = 5 , arr = [ 3 , 8 , 1 , 4 ] ; maxRightmostElement ( N , k , p , arr ) ;