Skip to main content
Back to problems
#2760
Easy Algorithms

Longest even odd subarray with threshold

Array Sliding Window
31.6% acceptance
Feb 25, 2026
356
289
You are given a 0-indexed integer array nums and an integer threshold. Find the length of the longest subarray of nums starting at index l and ending at index r (0 <= l <= r < nums.length) that satisfies the following conditions: nums[l] % 2 == 0 For all indices i in the range [l, r - 1], nums[i] % 2 != nums[i + 1] % 2 For all indices i in the range [l, r], nums[i] <= threshold Return an integer denoting the length of the longest such subarray. Note: A subarray is a contiguous non-empty sequence of elements within an array.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_alternating_subarray(nums: Vec<i32>, threshold: i32) -> i32 {
    let n = nums.len();
    let mut res = 0usize;
    let mut i = 0;
    while i < n {
      if nums[i] % 2 == 0 && nums[i] <= threshold {
        let mut j = i;
        while j + 1 < n && nums[j + 1] <= threshold && nums[j] % 2 != nums[j + 1] % 2 {
          j += 1;
        }
        res = res.max(j - i + 1);
        i = j + 1;
      } else {
        i += 1;
      }
    }
    res as i32
  }
}