845. 陣列中的最長山脈
阿新 • • 發佈:2020-10-25
我們把陣列 A 中符合下列屬性的任意連續子陣列 B 稱為 “山脈”:
B.length >= 3
存在 0 < i< B.length - 1 使得 B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(注意:B 可以是 A 的任意子陣列,包括整個陣列 A。)
給出一個整數陣列 A,返回最長 “山脈”的長度。
如果不含有 “山脈”則返回 0。
示例 1:
輸入:[2,1,4,7,3,2,5]
輸出:5
解釋:最長的 “山脈” 是 [1,4,7,3,2],長度為 5。
示例 2:
輸入:[2,2,2]
輸出:0
解釋:不含 “山脈”。
提示:
0 <= A.length <= 10000
0 <= A[i] <= 10000
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/longest-mountain-in-array
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
class Solution: def longestMountain(self, A: List[int]) -> int: n=len(A) if n<=2:return 0 L=R=0 res=0 for i in range(1,n-1): if A[i-1]<A[i] and A[i]>A[i+1]: l=i-1 r=i+1 while l>0 and A[l-1]<A[l]: l-=1 while r<n-1 and A[r]>A[r+1]: r+=1 res=max(res,r-l+1) return res