https://leetcode.com/problems/longest-mountain-in-array

Let us traverse our numbers and keep two variables: state and length, where:

  1. state is current state of our mountain: it is 0 in the beginning and also means that we can not start our mountain from given index. state equal to 1 means, that we are on increasing phase of our mountain and state equal 2 means, that we are on decreasing phase of our mountain.
  2. length is current length of mountain built so far.

Now, we need to carefully look at our states and see what we need to do in one or another situation:

  1. If state is equal to 0 or 1 and next element is more than current, it means we can continue to build increasing phase of mountain: so, we put state equal to 1 and increase length by 1.
  2. If state is equal to 2 and next element is more then curren, it means, that previous mountain just finished and we are currently buildind next mountain, for examle in 0,1,0,2,0: first mountain is 0,1,0 and second is 0,2,0. In this case we already build 2 elements of new mountain (mountains have 1 common element), so we put length = 2 and state = 1.
  3. If state is equal to 1 or 2 and next element is less than current, it means that we are on the decreasing phase of mountain: we put state = 2 and also increase length by 1. Note, that only here we need to update max_len, because our mountain is legible on this stage.
  4. Finally, if we have some other option: it is either next element is equal to current, or we have state 0 and next element is less than previous, we need put our state and length to values as we just started.

Complexity: time complexity is O(n), we make one pass over data, space complexity is O(1).

class Solution:
    def longestMountain(self, A):
        n, max_len = len(A), 0
        state, length = 0, 1
        for i in range(n-1):
            if state in [0, 1] and A[i+1] > A[i]:
                state, length = 1, length + 1
            elif state == 2 and A[i+1] > A[i]:
                state, length = 1, 2
            elif state in [1, 2] and A[i+1] < A[i]:
                state, length = 2, length + 1
                max_len = max(length, max_len)
            else:
                state, length = 0, 1
                
        return max_len

If you like the solution, you can upvote it on leetcode discussion section: Problem 0845