题目链接:https://leetcode-cn.com/problems/longest-mountain-in-array/
分析:
遍历数组。先找左边界,在左边界存在的条件下,更新右边界。相等时,索引+1,否则会死循环。当左右边界都存在时,更新最大长度。
Python
class Solution:
def longestMountain(self, A: List[int]) -> int:
left , right = -1, -1
i = 0
length = len(A)
res = 0
while i < length - 1:
while i<=length-2 and A[i] == A[i+1]:
i += 1
while i<=length-2 and A[i] < A[i+1]:
if left == -1:
left = i
i += 1
while i<=length-2 and A[i] > A[i+1]:
if left != -1:
right = i+1
i += 1
if left!=-1 and right!=-1:
res = max(res, right-left+1);
left, right = -1, -1
return res