Longest Mountain Subarray | Function to find the longest mountain subarray ; If the size of the array is less than 3 , the array won 't show  mountain like behaviour ; When a new mountain sub - array is found , there is a need to set the variables k , j to - 1 in order to help calculate the length of new mountain sub - array ; j marks the starting index of a new mountain sub - array . So set the value of j to current index i . ; Checks if next element is less than current element ; Checks if starting element exists or not , if the starting element of the mountain sub - array exists then the index of ending element is stored in k ; This condition checks if both starting index and ending index exists or not , if yes , the length is calculated . ; d holds the length of the longest mountain sub - array . If the current length is greater than the calculated length , then value of d is updated . ; Ignore if there is no increase or decrease in the value of the next element ; Checks and calculates the length if last element of the array is the last element of a mountain sub - array ; Driver code
def LongestMountain ( a ) : NEW_LINE INDENT i = 0 NEW_LINE j = - 1 NEW_LINE k = - 1 NEW_LINE p = 0 NEW_LINE d = 0 NEW_LINE n = 0 NEW_LINE if ( len ( a ) < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( len ( a ) - 1 ) : NEW_LINE INDENT if ( a [ i + 1 ] > a [ i ] ) : NEW_LINE INDENT if ( k != - 1 ) : NEW_LINE INDENT k = - 1 NEW_LINE j = - 1 NEW_LINE DEDENT if ( j == - 1 ) : NEW_LINE INDENT j = i NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i + 1 ] < a [ i ] ) : NEW_LINE INDENT if ( j != - 1 ) : NEW_LINE INDENT k = i + 1 NEW_LINE DEDENT if ( k != - 1 and j != - 1 ) : NEW_LINE INDENT if ( d < k - j + 1 ) : NEW_LINE INDENT d = k - j + 1 NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT k = - 1 NEW_LINE j = - 1 NEW_LINE DEDENT DEDENT DEDENT if ( k != - 1 and j != - 1 ) : NEW_LINE INDENT if ( d < k - j + 1 ) : NEW_LINE INDENT d = k - j + 1 NEW_LINE DEDENT DEDENT return d NEW_LINE DEDENT d = [ 1 , 3 , 1 , 4 , 5 , 6 , 7 , 8 , 9 , 8 , 7 , 6 , 5 ] NEW_LINE print ( LongestMountain ( d ) ) NEW_LINE