Farthest index that can be reached from the Kth index of given array by given operations | 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
function farthestHill ( arr , X , Y , N , K ) { var i , diff ; var pq = [ ] ; for ( i = K ; i < N - 1 ; i ++ ) { if ( arr [ i ] >= arr [ i + 1 ] ) continue ; diff = arr [ i + 1 ] - arr [ i ] ; pq . push ( diff ) ; pq . sort ( ) ; pq = pq . reverse ( ) ; if ( pq . length > Y ) { X -= pq [ 0 ] ; pq = pq . slice ( 1 ) ; } if ( X < 0 ) { document . write ( i ) ; return ; } } document . write ( N - 1 ) ; } var arr = [ 4 , 2 , 7 , 6 , 9 , 14 , 12 ] ; var X = 5 , Y = 1 ; var K = 0 ; var N = arr . length ; farthestHill ( arr , X , Y , N , K ) ;