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 Subarrays INPUT nums = [7, 6, 8, 1, 2] 7 i=0 6 i=1 8 i=2 1 i=3 2 i=4 Semi-Decreasing Subarray: First element STRICTLY greater than last element arr[0] > arr[n-1] Valid Examples: [7,6,1] : 7 > 1 (OK) [8,1] : 8 > 1 (OK) [8,1,2] : 8 > 2 (OK) [1,2] : 1 < 2 (INVALID) ALGORITHM STEPS 1 Group by Value Map each value to indices 8 --> [2], 7 --> [0] 6 --> [1], 2 --> [4], 1 --> [3] 2 Sort Values Descending Process larger values first 8 > 7 > 6 > 2 > 1 3 Track Min Start Index Keep smallest index seen min_idx updates: 2, 0, 0... Ensures first > last 4 Calculate Max Length len = current_idx - min_idx + 1 For val=1, idx=3: len = 3 - 0 + 1 = 4? Check! FINAL RESULT Longest Semi-Decreasing Subarray: 8 1 2 [8, 1, 2] from indices [2,3,4] Verification: 8 > 2 (OK - semi-decreasing) OUTPUT 3 Length of [8, 1, 2] = 3 This is the maximum length found in the array Key Insight: By grouping indices by their values and processing values in descending order, we ensure that when we reach a smaller value, all previously seen indices have larger values. Tracking the minimum start index allows O(n log n) time complexity instead of O(n^2) brute force approach. TutorialsPoint - Maximum Length of Semi-Decreasing Subarrays | Optimal Solution
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