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 ; Initializing ans to store Maximum valued rightmost element ; Calculating maximum value of Rightmost element ; returning rightmost element ; Driver Code ; Given Input ; Function Call
import java . io . * ; class GFG { static int maxRightmostElement ( int N , int k , int p , int arr [ ] ) { int ans = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { int d = Math . min ( arr [ i ] / p , k / ( N - 1 - i ) ) ; k -= d * ( N - 1 - i ) ; ans += d * p ; } return ans ; } 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 ) ) ; } }