Longest Subarrays having each Array element as the maximum | Function to find the maximum length of Subarrays for each element of the array having it as the maximum ; Initialize the bounds ; Iterate to find greater element on the left ; If greater element is found ; Decrement left pointer ; If boundary is exceeded ; Iterate to find greater element on the right ; If greater element is found ; Increment right pointer ; If boundary is exceeded ; Length of longest subarray where arr [ i ] is the largest ; Print the answer ; Driver Code
function solve ( n , arr ) { let i , ans = 0 ; for ( i = 0 ; i < n ; i ++ ) { let left = Math . max ( i - 1 , 0 ) ; let right = Math . min ( n - 1 , i + 1 ) ; while ( left >= 0 ) { if ( arr [ left ] > arr [ i ] ) { left ++ ; break ; } left -- ; } if ( left < 0 ) left ++ ; while ( right < n ) { if ( arr [ right ] > arr [ i ] ) { right -- ; break ; } right ++ ; } if ( right >= n ) right -- ; ans = 1 + right - left ; document . write ( ans + " " ) ; } } let arr = [ 4 , 2 , 1 ] ; let n = arr . length ; solve ( n , arr ) ;