Maximum Length of Semi-Decreasing Subarrays - Problem
Maximum Length of Semi-Decreasing Subarrays
You're given an integer array
What you need to do:
• Find the longest contiguous sequence where
• Return the length of this longest sequence
• Return
Example: In array
You're given an integer array
nums and need to find the longest semi-decreasing subarray. A subarray is semi-decreasing if its first element is strictly greater than its last element.What you need to do:
• Find the longest contiguous sequence where
first > last• Return the length of this longest sequence
• Return
0 if no such subarray existsExample: In array
[7,6,5,4], the entire array is semi-decreasing since 7 > 4, so the answer is 4. In array [1,2,3,4], no semi-decreasing subarray exists, so the answer is 0. Input & Output
example_1.py — Basic Case
$
Input:
[7,6,5,4]
›
Output:
4
💡 Note:
The entire array [7,6,5,4] is semi-decreasing since 7 > 4. This gives us the maximum length of 4.
example_2.py — No Semi-Decreasing
$
Input:
[1,2,3,4]
›
Output:
0
💡 Note:
No subarray exists where the first element is greater than the last element, so we return 0.
example_3.py — Mixed Values
$
Input:
[3,1,4,1,5]
›
Output:
4
💡 Note:
The subarray [3,1,4,1] has first element 3 > last element 1, giving length 4. Other valid subarrays like [3,1] have shorter lengths.
Visualization
Tap to expand
Understanding the Visualization
1
Scan the Mountain
Process each elevation point from left to right, tracking where each elevation first appears
2
Find Downhill Routes
For each point, check if you can create a longer downhill run by starting from any higher elevation seen earlier
3
Track Longest Run
Keep updating your record for the longest valid downhill run found so far
Key Takeaway
🎯 Key Insight: The longest semi-decreasing subarray will always start at the first occurrence of the highest value in the optimal pair and end at the current position of a smaller value, maximizing the distance between them.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, with each element processed once
✓ Linear Growth
Space Complexity
O(n)
HashMap to store the leftmost position of each unique value
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- A subarray must have at least 1 element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code