Leetcode #2863: Maximum Length of Semi-Decreasing Subarrays
In this guide, we solve Leetcode #2863 Maximum Length of Semi-Decreasing Subarrays in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer array nums. Return the length of the longest semi-decreasing subarray of nums, and 0 if there are no such subarrays.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Stack, Array, Sorting, Monotonic Stack
Intuition
We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.
Each element is pushed and popped at most once, yielding a linear-time scan.
Approach
Maintain a stack that is either increasing or decreasing, depending on the query.
When the invariant is broken, pop and resolve answers for those indices.
Steps:
- Scan elements once.
- Pop while the monotonic condition is violated.
- Use stack indices to update answers.
Example
Input: nums = [7,6,5,4,3,2,1,6,10,11]
Output: 8
Explanation: Take the subarray [7,6,5,4,3,2,1,6].
The first element is 7 and the last one is 6 so the condition is met.
Hence, the answer would be the length of the subarray or 8.
It can be shown that there aren't any subarrays with the given condition with a length greater than 8.
Python Solution
class Solution:
def maxSubarrayLength(self, nums: List[int]) -> int:
d = defaultdict(list)
for i, x in enumerate(nums):
d[x].append(i)
ans, k = 0, inf
for x in sorted(d, reverse=True):
ans = max(ans, d[x][-1] - k + 1)
k = min(k, d[x][0])
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.