Maximum Length of Semi-Decreasing Subarrays - Problem
Maximum Length of Semi-Decreasing Subarrays

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 exists

Example: 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
Mountain Ski Run Visualization7654Longest Downhill Run: 7→4 (Length=4)Algorithm Steps1. Start at peak 7 (elevation 7, position 0)2. Move to elevation 6: found downhill 7→6, length = 23. Move to elevation 5: found downhill 7→5, length = 34. Move to elevation 4: found downhill 7→4, length = 4 ✓Maximum Semi-Decreasing Subarray Length: 4
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

n
2n
Linear Growth
Space Complexity
O(n)

HashMap to store the leftmost position of each unique value

n
2n
Linearithmic Space

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • A subarray must have at least 1 element
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
34.4K Views
Medium Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen