Find the length of the longest contiguous subarray that is either strictly increasing or strictly decreasing.
Given an integer array nums, return the length of the longest contiguous subarray that is either:
- strictly increasing: every element is greater than the previous one, or
- strictly decreasing: every element is smaller than the previous one.
A subarray must consist of consecutive elements from the original array.
Your task is to identify the maximum length among all such monotonic subarrays.
Input Format
- A single integer array
nums. nums[i]is an integer value at indexi.
Output Format
- Return one integer: the maximum length of a contiguous strictly increasing or strictly decreasing subarray.
Constraints
1 <= nums.length- The array may contain duplicate values.
- A valid subarray must be contiguous.
- If no adjacent pair extends a monotonic run, the answer is
1.
Example 1
Input
nums = [1,2,3,2,1,0,4]
Output
4
Explanation
The longest strictly decreasing subarray is [3,2,1,0], which has length 4.
Example 2
Input
nums = [5,5,5]
Output
1
Explanation
No adjacent pair is strictly increasing or strictly decreasing, so the best subarray has length 1.
Show 1 more example
Example 3
Input
nums = [1,3,5,4,2]
Output
3
Explanation
The longest strictly increasing subarray is [1,3,5] and the longest strictly decreasing subarray is [5,4,2]. Both have length 3.
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.