leetcode978 最长湍流子数组 中等

题目:
在这里插入图片描述
题目链接

思路:
我使用动态规划的做法
题目提供了两种方案,那么每一步都考虑用哪种方案最好,使用两个dp数组记录当前位置i的最长湍流子数组长度
以实例1为例:
9>4且9在偶数位置上所以优先考虑方案2,所以方案1是不符合的,为1,故two[i] = 2, one[i] = 1
4>2且4在奇数位置上所以优先考虑方案1,所以方案2是不符合的,为1,此时方案1要考虑前一个数的最长湍流子数组长,其值+1与2比较谁大,谁大dp[i]就等于谁,因为要求最长,所以要看前面的位置能不能和当前位置连起来构成子数组
剩下同理

class Solution {
    public int maxTurbulenceSize(int[] A) {
        if(A == null || A.length == 0){
            return 0;
        }
        if(A.length == 1){
            return 1;
        }
        int len = A.length;
        int[] ruleOne = new int[len];
        int[] ruleTwo = new int[len];
        int max = 0;
        for(int i = 0; i < len-1; i++){
            //偶数
            if(i%2 == 0){
                if(A[i] > A[i+1]){
                    if(i == 0){
                        ruleTwo[i] = 2;
                        ruleOne[i] = 1;
                    }else{
                        ruleTwo[i] = Math.max(ruleTwo[i-1]+1, 2);
                        ruleOne[i] = 1;
                    }
                }else if(A[i] < A[i+1]){
                    if(i == 0){
                        ruleOne[i] = 2;
                        ruleTwo[i] = 1;
                    }else{
                        ruleOne[i] = Math.max(ruleOne[i-1]+1, 2);
                        ruleTwo[i] = 1;
                    }
                }else{
                    //相等
                    ruleOne[i] = ruleTwo[i] = 1;
                }
            }else{
                //奇数

                if(A[i] > A[i+1]){
                    if(i == 0){
                        ruleOne[i] = 2;
                        ruleTwo[i] = 1;
                    }else{
                        ruleOne[i] = Math.max(ruleOne[i-1]+1, 2);
                        ruleTwo[i] = 1;
                    }
                }else if(A[i] < A[i+1]){
                    if(i == 0){
                        ruleTwo[i] = 2;
                        ruleOne[i] = 1;
                    }else{
                        ruleTwo[i] = Math.max(ruleTwo[i-1]+1, 2);
                        ruleOne[i] = 1;
                    }
                }else{
                    //相等
                    ruleOne[i] = ruleTwo[i] = 1;
                }
            }
            max = Math.max(max, Math.max(ruleOne[i], ruleTwo[i]));
        }
        return max;
    }
}

此题解法有更有解,可以参考其他人的题解,这里我只讲动态规划的做法
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值