845. Longest Mountain in Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012033124/article/details/81350187

https://leetcode.com/problems/longest-mountain-in-array/description/
找最长的山脉
思路:一次遍历,找山顶(比两端都高)。若找到,从山顶向两端发散,求山脉长度,每次更新最大长度。

class Solution:
    def longestMountain(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        n = len(A)
        maxL = 0
        for i in range(n):
            length = 0  #山脉长度
            #找到山顶
            if i-1 >= 0 and i+1 < n and A[i] > A[i-1] and A[i] > A[i+1]:
                length += 1
                left = right = i  #山顶左右两侧指针
                while left-1 >= 0 and A[left] > A[left-1]:
                    left -= 1
                    length += 1
                while right+1 < n and A[right] > A[right+1]:
                    right += 1
                    length += 1
            maxL = max(length, maxL)
        return maxL

猜你喜欢

转载自blog.csdn.net/u012033124/article/details/81350187