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
def farthestHill ( arr , X , Y , N , K ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( K , N - 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] >= arr [ i + 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT diff = arr [ i + 1 ] - arr [ i ] NEW_LINE pq . append ( diff ) NEW_LINE if ( len ( pq ) > Y ) : NEW_LINE INDENT X -= pq [ - 1 ] NEW_LINE pq [ - 1 ] NEW_LINE DEDENT if ( X < 0 ) : NEW_LINE INDENT print ( i ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( N - 1 ) NEW_LINE DEDENT arr = [ 4 , 2 , 7 , 6 , 9 , 14 , 12 ] NEW_LINE X = 5 NEW_LINE Y = 1 NEW_LINE K = 0 NEW_LINE N = len ( arr ) NEW_LINE farthestHill ( arr , X , Y , N , K ) NEW_LINE