Longest Strictly Increasing or Strictly Decreasing Subarray - Problem
Given an array of integers nums, you need to find the longest contiguous subarray that is either strictly increasing or strictly decreasing.
A subarray is strictly increasing if each element is greater than the previous one (no equal elements allowed). Similarly, a subarray is strictly decreasing if each element is smaller than the previous one.
Goal: Return the maximum length among all such subarrays.
Example: In array [1, 3, 2, 4], we have increasing subarray [1, 3] of length 2, and decreasing subarray [3, 2] of length 2. The answer is 2.
Input & Output
example_1.py โ Basic Increasing and Decreasing
$
Input:
[1,3,2,4]
โบ
Output:
2
๐ก Note:
The array contains [1,3] (increasing, length 2) and [3,2] (decreasing, length 2). Both have length 2, so the answer is 2.
example_2.py โ Longer Increasing Sequence
$
Input:
[1,2,3,4,5,3,2,1]
โบ
Output:
5
๐ก Note:
The longest subarray is [1,2,3,4,5] which is strictly increasing with length 5. There's also [5,3,2,1] (decreasing, length 4), but 5 is larger.
example_3.py โ Single Element
$
Input:
[5]
โบ
Output:
1
๐ก Note:
A single element forms a subarray of length 1, which is considered both increasing and decreasing.
Constraints
- 1 โค nums.length โค 105
- -109 โค nums[i] โค 109
- Note: Single element subarrays have length 1
Visualization
Tap to expand
Understanding the Visualization
1
Start the Journey
Begin at the first elevation point with both uphill and downhill counters set to 1
2
Track Direction Changes
As you move, increment the appropriate counter based on elevation change
3
Reset on Direction Change
When switching from uphill to downhill (or vice versa), reset the opposite counter
4
Record Maximum
Keep track of the longest consistent segment you've encountered
Key Takeaway
๐ฏ Key Insight: Track both increasing and decreasing trends simultaneously in one pass, resetting counters when direction changes - this gives us O(n) optimal performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code