1680. Longest Floor-First Stretch
A hiker records elevations along a trail in nums. A stretch is a non-empty contiguous run of readings, and it is floor-first when its first reading is less than or equal to every other reading in the stretch. Return the length of the longest floor-first stretch.
For each index i, find the nearest index to the right holding a strictly smaller value; the longest floor-first stretch starting at i ends just before that index, or at the end of the array when there is none. A monotonic stack finds all these indices in a single pass, giving O(n) time and O(n) space, where n = nums.length. Equal values do not end a stretch. Constraints: 1 <= n <= 1000 and -10^9 <= nums[i] <= 10^9.
Example 1
- Input:
- nums = [4,6,5,2,9]
- Output:
- 3
- Explanation:
Starting at 4 the stretch 4,6,5 has length 3 and ends before the smaller 2; no stretch is longer.
Example 2
- Input:
- nums = [7,7,7]
- Output:
- 3
- Explanation:
Equal values are allowed, so the whole array is floor-first.
Example 3
- Input:
- nums = [5,4,3,2,1]
- Output:
- 1
- Explanation:
Every next value is strictly smaller, so each stretch has length 1.
Constraints
1 ≤ nums.length ≤ 1000; -109 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)