Maximum Length of Semi-Decreasing Subarrays - 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.

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [7,6,8,1,2]
Output: 3
💡 Note: The subarray [8,1,2] has first element 8 > last element 2, with length 3. This is the longest such subarray.
Example 2 — No Semi-Decreasing
$ Input: nums = [1,2,3,4]
Output: 0
💡 Note: All elements are in increasing order, so no subarray has first > last. Return 0.
Example 3 — Single Decreasing Pair
$ Input: nums = [5,1]
Output: 2
💡 Note: The entire array [5,1] is semi-decreasing since 5 > 1, length is 2.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Maximum Length of Semi-Decreasing SubarraysInput Array:76812Semi-Decreasing Subarray:8128 > 2 ✓ (first > last)Length = 3Output: 3
Understanding the Visualization
1
Input Array
Given array [7,6,8,1,2]
2
Find Semi-Decreasing
Check subarrays where first > last
3
Return Max Length
Longest valid subarray has length 3
Key Takeaway
🎯 Key Insight: We need to find the longest contiguous subarray where the first element is strictly greater than the last element
Asked in
Google 25 Microsoft 18 Amazon 15
12.0K Views
Medium Frequency
~25 min Avg. Time
520 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