2760. 最长奇偶子数组 --力扣 --JAVA

题目

给你一个下标从 0 开始的整数数组 nums 和一个整数 threshold 。

请你从 nums 的子数组中找出以下标 l 开头、下标 r 结尾 (0 <= l <= r < nums.length) 且满足以下条件的 最长子数组 :

numsl % 2 == 0

对于范围 l, r - 1 内的所有下标 i ,numsi % 2 != numsi + 1 % 2

对于范围 l, r 内的所有下标 i ,numsi <= threshold

以整数形式返回满足题目要求的最长子数组的长度。

注意:子数组 是数组中的一个连续非空元素序列。

解题思路

  1. 双层循环,三个条件依次判断,进行累加记录。

代码展示

java 复制代码
public class Zero {
    public static void main(String[] args) {
        Zero zero = new Zero();
        System.out.println(zero.longestAlternatingSubarray(new int[]{3,2,5,4}, 5));
        System.out.println(zero.longestAlternatingSubarray(new int[]{1,2}, 2));
        System.out.println(zero.longestAlternatingSubarray(new int[]{2,3,4,5}, 4));
    }
    public int longestAlternatingSubarray(int[] nums, int threshold) {
        int ans = 0;
        for (int i = 0; i < nums.length; i++){
            if(nums[i] % 2 != 0 || nums[i] > threshold){
                continue;
            }
            int count = 1;
            for (int j = i + 1; j < nums.length; j++){
                if(nums[j] % 2 == nums[j - 1] % 2){
                    break;
                }
                if(nums[j] > threshold){
                    break;
                }
                count++;
            }
            ans = Math.max(ans, count);
        }
        return ans;
    }
}
相关推荐
玛卡巴卡ldf14 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
wanzehongsheng15 小时前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
KobeSacre15 小时前
CyclicBarrier 源码
java·jvm·算法
手写码匠15 小时前
注意力机制全家桶:从 Multi-Head 到 GQA 再到 Flash Attention 的手写实现
人工智能·深度学习·算法·aigc
学究天人16 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷3.2)
线性代数·算法·机器学习·数学建模·动态规划·抽象代数·拓扑学
Yang_jie_0316 小时前
笔记:数据结构(链队列的相关判断条件)
数据结构·笔记
tkevinjd16 小时前
力扣322-零钱兑换
算法·leetcode·动态规划
大鱼>16 小时前
AI+资产监控:农业设施智能监控系统
人工智能·深度学习·算法·机器学习
AI科技星16 小时前
乖乖数学·全域超复数统一场论:五大核心门槛与全套标准定量数据
人工智能·python·算法·金融·全域数学
Frostnova丶17 小时前
(13)LeetCode 53. 最大子数组和
算法·leetcode·职场和发展