[
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:
state
is current state of our mountain: it is0
in the beginning and also means that we can not start our mountain from given index.state
equal to1
means, that we are on increasing phase of our mountain andstate
equal2
means, that we are on decreasing phase of our mountain.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:
- If
state
is equal to0
or1
and next element is more than current, it means we can continue to build increasing phase of mountain: so, we putstate
equal to1
and increaselength
by1
. - If
state
is equal to2
and 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,0
and second is0,2,0
. In this case we already build2
elements of new mountain (mountains have1
common element), so we putlength = 2
andstate = 1
. - If
state
is equal to1
or2
and next element is less than current, it means that we are on the decreasing phase of mountain: we putstate = 2
and also increaselength
by1
. 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
0
and next element is less than previous, we need put ourstate
andlength
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