Maximum Length of Semi-Decreasing Subarrays Problem
#2863
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2863.
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.
- A subarray is a contiguous non-empty sequence of elements within an array.
- A non-empty array is semi-decreasing if its first element is strictly greater than its last element.
Example 1:
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.
Example 2:
Input: nums = [57,55,50,60,61,58,63,59,64,60,63]
Output: 6
Explanation: Take the subarray [61,58,63,59,64,60].
The first element is 61 and the last one is 60 so the condition is met.
Hence, the answer would be the length of the subarray or 6.
It can be shown that there aren't any subarrays with the given condition with a length greater than 6.
Example 3:
Input: nums = [1,2,3,4]
Output: 0
Explanation: Since there are no semi-decreasing subarrays in the given array, the answer is 0.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Hash Table + Sorting
A subarray is semi-decreasing when its first element is larger than its last, so we want the farthest pair i < j with nums[i] > nums[j].
Store the indices of every value in a hash table. Visit the distinct values from largest to smallest while keeping k, the smallest index among all larger values seen so far. For value x, the farthest partner is its last occurrence, giving length last(x) - k + 1 (ignored when not positive). Then update k with the first occurrence of x.
Complexity: time O(n log n), space O(n).
from collections import defaultdict
from math import inf
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