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 | Java implementation of the above approach ; 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 stack is not empty and top element is less than or equal to preMin [ j ] ; Remove the top element ; If stack is not empty and top element of the stack is less than the current element ; Push the arr [ j ] in stack ; If none of the above case satisfy then return " No " ; Driver code ; Input
import java . io . * ; import java . util . * ; class GFG { static String recreationalSpot ( int arr [ ] , int N ) { if ( N < 3 ) { return " No " ; } int preMin [ ] = new int [ N ] ; preMin [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { preMin [ i ] = Math . min ( preMin [ i - 1 ] , arr [ i ] ) ; } Stack < Integer > stack = new Stack < Integer > ( ) ; for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( arr [ j ] > preMin [ j ] ) { while ( stack . empty ( ) == false && stack . peek ( ) <= preMin [ j ] ) { stack . pop ( ) ; } if ( stack . empty ( ) == false && stack . peek ( ) < arr [ j ] ) { return " Yes " ; } stack . push ( arr [ j ] ) ; } } return " No " ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 7 , 11 , 5 , 13 , 2 } ; int size = arr . length ; System . out . println ( recreationalSpot ( arr , size ) ) ; } }