LeetCode 845. 数组中的最长山脉(C++、python)

我们把数组 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
解释:不含 “山脉”。

C++

class Solution {
public:
    int longestMountain(vector<int>& A) 
    {
        int n=A.size();
        if(n<3)
        {
            return 0;
        }
        int res=0;
        for(int i=1;i<n-1;i++)
        {
            if(A[i-1]<A[i] && A[i+1]<A[i])
            {
                int count=1;
                int left=i-1;
                int right=i+1;
                while(left>=0)
                {
                    if(A[left]<A[left+1])
                    {
                        count++;
                        left--;
                    }
                    else
                    {
                        break;
                    }
                }
                while(right<n)
                {
                    if(A[right]<A[right-1])
                    {
                        count++;
                        right++;
                    }
                    else
                    {
                        break;
                    }                    
                }
                res=max(res,count);
            }
        }
        return res;
    }
};

python

class Solution:
    def longestMountain(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        n=len(A)
        if n<3:
            return 0
        res=0
        for i in range(1,n-1):
            if A[i-1]<A[i] and A[i+1]<A[i]:
                count=1
                left=i-1
                right=i+1
                while left>=0:
                    if A[left]<A[left+1]:
                        count+=1
                        left-=1
                    else:
                        break
                while right<n:
                    if A[right]<A[right-1]:
                        count+=1
                        right+=1
                    else:
                        break
                res=max(res,count)
        return res
        

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/84714626