Farthest index that can be reached from the Kth index of given array by given operations | C ++ program for the above approach ; Function to find the farthest index that can be reached ; Declare a priority queue ; Iterate the array ; If current element is greater than the next element ; Otherwise , store their difference ; Push diff into pq ; If size of pq exceeds Y ; Decrease X by the top element of pq ; Remove top of pq ; If X is exhausted ; Current index is the farthest possible ; Print N - 1 as farthest index ; Driver Code ; Function Call ;
# include < bits / stdc ++ . h > using namespace std ; void farthestHill ( int arr [ ] , int X , int Y , int N , int K ) { int i , diff ; priority_queue < int > pq ; for ( i = K ; i < N - 1 ; i ++ ) { if ( arr [ i ] >= arr [ i + 1 ] ) continue ; diff = arr [ i + 1 ] - arr [ i ] ; pq . push ( diff ) ; if ( pq . size ( ) > Y ) { X -= pq . top ( ) ; pq . pop ( ) ; } if ( X < 0 ) { cout << i ; return ; } } cout << N - 1 ; } int main ( ) { int arr [ ] = { 4 , 2 , 7 , 6 , 9 , 14 , 12 } ; int X = 5 , Y = 1 ; int K = 0 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; farthestHill ( arr , X , Y , N , K ) ; return 0 ; } ]