Maximize the rightmost element of an array in k operations in Linear Time | Java program for the above approach ; 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 ; returning the rightmost element ; Driver Code ; Given Input ; Function Call
import java . io . * ; class GFG { static int maxRightmostElement ( int N , int k , int p , int arr [ ] ) { while ( k > 0 ) { for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] >= p ) { arr [ i ] = arr [ i ] - p ; arr [ i + 1 ] = arr [ i + 1 ] + p ; break ; } } k -- ; } return arr [ N - 1 ] ; } public static void main ( String [ ] args ) { int N = 4 , k = 5 , p = 2 ; int arr [ ] = { 3 , 8 , 1 , 4 } ; System . out . println ( maxRightmostElement ( N , k , p , arr ) ) ; } }