Longest Subarrays having each Array element as the maximum | Java Program to implement the above approach ; 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
import java . util . * ; class GFG { static void solve ( int n , int arr [ ] ) { int i , ans = 0 ; for ( i = 0 ; i < n ; i ++ ) { int left = Math . max ( i - 1 , 0 ) ; int 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 ; System . out . print ( ans + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 1 } ; int n = arr . length ; solve ( n , arr ) ; } }