Maximum Length of Semi-Decreasing Subarrays — LeetCode 2863 Python Solution
MediumLeetCode PremiumStackArraySortingMonotonic Stack
- Problem
- #2863
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
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].
Python solution
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays?
- LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays cover?
- LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays is tagged Stack, Array, Sorting and Monotonic Stack on LeetCode.
- Is LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays a premium problem?
- Yes. LeetCode 2863. Maximum Length of Semi-Decreasing Subarrays is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.