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 ; Initialise 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
def solve ( n , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left = max ( i - 1 , 0 ) NEW_LINE right = min ( n - 1 , i + 1 ) NEW_LINE while left >= 0 : NEW_LINE INDENT if arr [ left ] > arr [ i ] : NEW_LINE INDENT left += 1 NEW_LINE break NEW_LINE DEDENT left -= 1 NEW_LINE DEDENT if left < 0 : NEW_LINE INDENT left += 1 NEW_LINE DEDENT while right < n : NEW_LINE INDENT if arr [ right ] > arr [ i ] : NEW_LINE INDENT right -= 1 NEW_LINE break NEW_LINE DEDENT right += 1 NEW_LINE DEDENT if right >= n : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT ans = 1 + right - left NEW_LINE print ( ans , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 4 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE solve ( n , arr ) NEW_LINE