[leetcode] 845. Longest Mountain in Array

本文介绍了一种算法,用于寻找数组中符合山脉特性的最长子数组。山脉子数组需满足至少三个元素,且存在一个峰值,两侧分别递增和递减。通过一次遍历,该算法能高效解决问题,适用于数据结构与算法学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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.

Note:

  1. 0 <= A.length <= 10000
  2. 0 <= A[i] <= 10000

Follow up:

  • Can you solve it using only one pass?
  • Can you solve it in O(1) space?

分析

题目的意思是:找出一个数组中的mountain array。

  • 大致思路是把每一个位置当成起点,然后先找up上升趋势的值,然后找下降趋势的值,这样就能找到一个mountain array,我们更新res来找到所有mountain array中最长的array的长度。

代码

class Solution {
public:
    int longestMountain(vector<int>& A) {
        int n=A.size();
        int res=0;
        int base=0;
        while(base<n){
            int end=base;
            if(end+1<n&&A[end]<A[end+1]){
                while(end+1<n&&A[end]<A[end+1]) end++;  //up
                if(end+1<n&&A[end]>A[end+1]){
                    while(end+1<n&&A[end]>A[end+1]) end++;  //down
                    res=max(res,end-base+1);
                }
            }
            base=max(base+1,end);
        }
        return res;
    }
};

参考文献

845. Longest Mountain in Array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值