Longest Even Odd Subarray With Threshold - Problem
Imagine you're analyzing a sequence of numbers to find the perfect alternating pattern! You need to find the longest contiguous subarray that satisfies three strict conditions:
- Must start with an even number - This is your entry point
- Must alternate between even and odd - Like a perfect zigzag pattern
- All numbers must be ≤ threshold - Stay within the limit!
Given an integer array nums and an integer threshold, return the length of the longest such magical subarray.
Example: For nums = [3,2,5,4] and threshold = 5, the subarray [2,5,4] starting at index 1 has length 3 - it starts with even number 2, alternates (2→5→4), and all numbers ≤ 5.
Input & Output
example_1.py — Basic Example
$
Input:
nums = [3,2,5,4], threshold = 5
›
Output:
3
💡 Note:
The subarray [2,5,4] starting at index 1 satisfies all conditions: starts with even number 2, alternates (2→5→4), and all elements ≤ 5.
example_2.py — No Valid Subarray
$
Input:
nums = [1,2], threshold = 2
›
Output:
1
💡 Note:
The subarray [2] at index 1 is the only valid one. [1,2] doesn't work because it doesn't start with an even number.
example_3.py — Threshold Violation
$
Input:
nums = [2,3,4,5], threshold = 4
›
Output:
3
💡 Note:
The subarray [2,3,4] has length 3. We can't include 5 because it exceeds the threshold of 4.
Constraints
- 1 ≤ nums.length ≤ 100
- 1 ≤ nums[i] ≤ 100
- 1 ≤ threshold ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Start with Left Foot
Every valid sequence must begin with a 'left foot' dancer (even number)
2
Alternate Perfectly
Dancers must alternate left-right-left-right (even-odd-even-odd) throughout
3
Height Limit
No dancer can exceed the maximum height (threshold) allowed
4
Find Longest Sequence
Among all possible valid sequences, find the one with the most dancers
Key Takeaway
🎯 Key Insight: We only need to track the current valid sequence length, not the actual elements. Reset when rules break, extend when they hold!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code