Check if a triplet of buildings can be selected such that the third building is taller than the first building and smaller than the second building | Function to check if it is possible to select three buildings that satisfy the given condition ; Stores prefix min array ; Iterate over the range [ 1 , N - 1 ] ; Stores the element from the ending in increasing order ; Iterate until j is greater than or equal to 0 ; If current array element is greater than the prefix min upto j ; Iterate while st is not empty and top element is less than or equal to preMin [ j ] ; Remove the top element ; If st is not empty and top element of the st is less than the current element ; Push the arr [ j ] in st ; If none of the above case satisfy then return " No " ; Input
function recreationalSpot ( arr , N ) { if ( N < 3 ) { return " " ; } var preMin = new Array ( N ) ; preMin [ 0 ] = arr [ 0 ] ; var i ; for ( i = 1 ; i < N ; i ++ ) { preMin [ i ] = Math . min ( preMin [ i - 1 ] , arr [ i ] ) ; } var st = [ ] ; var j ; for ( j = N - 1 ; j >= 0 ; j -- ) { if ( arr [ j ] > preMin [ j ] ) { while ( st . length > 0 && st [ st . length - 1 ] <= preMin [ j ] ) { st . pop ( ) ; } if ( st . length > 0 && st [ st . length - 1 ] < arr [ j ] ) { return " " ; } st . push ( arr [ j ] ) ; } } return " " ; } var arr = [ 4 , 7 , 11 , 5 , 13 , 2 ] ; var size = arr . length ; document . write ( recreationalSpot ( arr , size ) ) ;