Find whether a subarray is in form of a mountain or not | Utility method to construct left and right array ; initialize first left index as that index only ; if current value is greater than previous , update last increasing ; initialize last right index as that index only ; if current value is greater than next , update first decreasing ; method returns true if arr [ L . . R ] is in mountain form ; return true only if right at starting range is greater than left at ending range ; Driver Code
function preprocess ( arr , N , left , right ) { left [ 0 ] = 0 ; let lastIncr = 0 ; for ( let i = 1 ; i < N ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) lastIncr = i ; left [ i ] = lastIncr ; } right [ N - 1 ] = N - 1 ; let firstDecr = N - 1 ; for ( let i = N - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] ) firstDecr = i ; right [ i ] = firstDecr ; } } function isSubarrayMountainForm ( arr , left , right , L , R ) { return ( right [ L ] >= left [ R ] ) ; } let arr = [ 2 , 3 , 2 , 4 , 4 , 6 , 3 , 2 ] ; let N = arr . length ; let left = new Array ( N ) ; let right = new Array ( N ) ; preprocess ( arr , N , left , right ) ; let L = 0 ; let R = 2 ; if ( isSubarrayMountainForm ( arr , left , right , L , R ) ) document . write ( " " + " " + " " ) ; else document . write ( " " + " " + " " ) ; L = 1 ; R = 3 ; if ( isSubarrayMountainForm ( arr , left , right , L , R ) ) document . write ( " " + " " ) ; else document . write ( " " + " " ) ;