leetcode 376.Wiggle Subsequence (greedy O(n))

本文介绍了一种求解最长摇摆子序列的算法,通过分析数组中元素的升降趋势,利用贪心策略或动态规划思想,记录上升和下降序列的长度,最终找到最长的摇摆子序列长度。

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

A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

给出一个数组,让判断最长的摇摆子序列长度,即元素保持一升一降

思路:
greedy 或者dp
感觉greedy也可以说是简化版的dp

记录下两个方向up和down,用变量表示,(dp的话就是保存下所有的up,down值,数组长度)

初始状态up,down都是1
比如[1,2,3,4,2]
刚开始到2的时候上升,所以up=down + 1 = 2
然后3和4的时候一路上升,因为只是上升,趋势没有变,down仍然停留在1,up由down决定,也不变
后面到最后一个2的时候,下降,下降次数由上一个上升次数决定,down=up+1
(因为是摇摆序列,没有上升就没有下降,没有下降就没有上升)

注意当数组长度是0的时候,因为up和down初始值都是1,所以取min(n, max(up, down))

    public int wiggleMaxLength(int[] nums) {
       if (nums == null) {
           return 0;
       } 
        
        int up = 1;
        int down = 1;
        
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                up = down + 1;
            } else if (nums[i] < nums[i - 1]) {
                down = up + 1;
            }
        }
        
        return Math.min(nums.length, Math.max(up, down));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值