题目大意
先up再down找序列中最长山脉的长度。
Let’s call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < … B[i-1] < B[i] > B[i+1] > … > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
题目解析
遍历一次,采用计数的方法。
如果遇到up的时候,lastup计数+1
如果遇到down的时候,更新变量确定前面部分是否有up,lastdown计数+1,如果前面已经有山脉的up子序列,则已经构成山脉,更新ans。
代码
class Solution:
def longestMountain(self, A: List[int]) -> int:
lastup = lastdown = ans = sub = 0
for i in range(1, len(A)):
if A[i]-A[i-1] > 0:
lastdown = sub = 0
lastup += 1
elif A[i]-A[i-1] < 0:
sub = max(sub, lastup)
lastup = 0
lastdown += 1
if sub > 0:
ans = max(ans, sub+lastdown+1)
else:
lastdown = lastup = sub = 0
return ans