[Leetcode] 845. Longest Mountain in Array (Python)

[Leetcode] 845. Longest Mountain in Array

题目大意

先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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值