Find maximum of minimum for every window size in a given array | An efficient Javascript program to find maximum of all minimums of windows of different size ; Used to find previous and next smaller ; Arrays to store previous and next smaller ; Initialize elements of left [ ] and right [ ] ; Fill elements of left [ ] using logic discussed on www . geeksforgeeks . org / next - greater - element / https : ; Empty the stack as stack is going to be used for right [ ] ; Fill elements of right [ ] using same logic ; Create and initialize answer array ; Fill answer array by comparing minimums of all lengths computed using left [ ] and right [ ] ; length of the interval ; arr [ i ] is a possible answer for this length ' len ' interval , check x if arr [ i ] is more than max for ' len ' ; Some entries in ans [ ] may not be filled yet . Fill them by taking values from right side of ans [ ] ; Print the result
let arr = [ 10 , 20 , 30 , 50 , 10 , 70 , 30 ] ; function printMaxOfMin ( n ) { let s = [ ] ; let left = new Array ( n + 1 ) ; left . fill ( 0 ) ; let right = new Array ( n + 1 ) ; right . fill ( 0 ) ; for ( let i = 0 ; i < n ; i ++ ) { left [ i ] = - 1 ; right [ i ] = n ; } for ( let i = 0 ; i < n ; i ++ ) { while ( s . length > 0 && arr [ s [ s . length - 1 ] ] >= arr [ i ] ) { s . pop ( ) ; } if ( s . length > 0 ) { left [ i ] = s [ s . length - 1 ] ; } s . push ( i ) ; } while ( s . length > 0 ) { s . pop ( ) ; } for ( let i = n - 1 ; i >= 0 ; i -- ) { while ( s . length > 0 && arr [ s [ s . length - 1 ] ] >= arr [ i ] ) { s . pop ( ) ; } if ( s . length > 0 ) { right [ i ] = s [ s . length - 1 ] ; } s . push ( i ) ; } let ans = new Array ( n + 1 ) ; ans . fill ( 0 ) ; for ( let i = 0 ; i <= n ; i ++ ) { ans [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { let len = right [ i ] - left [ i ] - 1 ; ans [ len ] = Math . max ( ans [ len ] , arr [ i ] ) ; } for ( let i = n - 1 ; i >= 1 ; i -- ) { ans [ i ] = Math . max ( ans [ i ] , ans [ i + 1 ] ) ; } for ( let i = 1 ; i <= n ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } printMaxOfMin ( arr . length ) ;