Maximize the rightmost element of an array in k operations in Linear Time | C ++ program for above approach ; Function to calculate maximum value of Rightmost element ; Initializing ans to store Maximum valued rightmost element ; Calculating maximum value of Rightmost element ; Printing rightmost element ; Driver Code ; Given Input ; Function Call
#include <iostream> NEW_LINE using namespace std ; void maxRightmostElement ( int N , int k , int arr [ ] ) { int ans = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { int d = min ( arr [ i ] / 2 , k / ( N - 1 - i ) ) ; k -= d * ( N - 1 - i ) ; ans += d * 2 ; } cout << ans << endl ; } int main ( ) { int N = 4 , k = 5 , arr [ ] = { 3 , 8 , 1 , 4 } ; maxRightmostElement ( N , k , arr ) ; return 0 ; }