Find the longest contiguous subarray that starts with an even number, alternates even and odd values, and every element is at most a given threshold.
Given an integer array nums and an integer threshold, find the length of the longest contiguous subarray that satisfies all of the following:
- The first element of the subarray is even.
- The parity of adjacent elements alternates throughout the subarray.
- Every element in the subarray is less than or equal to
threshold.
Return the maximum possible length of such a subarray. If no valid subarray exists, return 0.
A subarray must be contiguous.
Input Format
nums: an array of integersthreshold: an integer
You may assume the input is already provided in the platform's standard function signature.
Output Format
- Return a single integer: the maximum length of a valid subarray.
Constraints
- The answer must be based on a contiguous subarray.
- All elements in a valid subarray must satisfy
nums[i] <= threshold. - The first element of a valid subarray must be even.
- Adjacent elements in a valid subarray must alternate in parity.
- If no valid subarray exists, return
0.
Example 1
Input
nums = [3,2,5,4], threshold = 5
Output
3
Explanation
The subarray [2,5,4] is valid: it starts with an even number, alternates parity, and all values are at most 5.
Example 2
Input
nums = [1,2], threshold = 2
Output
1
Explanation
The subarray [2] is valid. [1,2] is invalid because it starts with an odd number.
Show 1 more example
Example 3
Input
nums = [4,10,2], threshold = 6
Output
1
Explanation
Only [4] is valid. The other elements exceed the threshold.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.