[
two pointers
array
]
Leetcode 0845. Longest Mountain in Array
https://leetcode.com/problems/longest-mountain-in-array
Let us traverse our numbers and keep two variables: state and length, where:
stateis current state of our mountain: it is0in the beginning and also means that we can not start our mountain from given index.stateequal to1means, that we are on increasing phase of our mountain andstateequal2means, that we are on decreasing phase of our mountain.lengthis 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:
- If
stateis equal to0or1and next element is more than current, it means we can continue to build increasing phase of mountain: so, we putstateequal to1and increaselengthby1. - If
stateis equal to2and next element is more then curren, it means, that previous mountain just finished and we are currently buildind next mountain, for examle in0,1,0,2,0: first mountain is0,1,0and second is0,2,0. In this case we already build2elements of new mountain (mountains have1common element), so we putlength = 2andstate = 1. - If
stateis equal to1or2and next element is less than current, it means that we are on the decreasing phase of mountain: we putstate = 2and also increaselengthby1. Note, that only here we need to updatemax_len, because our mountain is legible on this stage. - Finally, if we have some other option: it is either next element is equal to current, or we have state
0and next element is less than previous, we need put ourstateandlengthto 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