NeetCode #49LC-3105EasyArrays & Hashing
← Back to All Problems#49 · #3105 · Longest Strictly Increasing or Strictly Decreasing Subarray(最长的严格递增或递减子数组)
📌 Problem Statement & Constraints
Given an array of integers
nums, return the length of the longest subarray that is either strictly increasing or strictly decreasing. Constraints: 1 <= nums.length <= 50, 1 <= nums[i] <= 50.💡 Core Algorithmic Approaches
- Track two running lengths:
incfor the current strictly increasing run anddecfor the strictly decreasing run. - Compare each element with its predecessor. If
nums[i] > nums[i-1], extendincand resetdecto 1; if smaller, extenddecand resetinc; if equal, reset both to 1. - The answer is the maximum of both counters over the whole scan.
- Because a subarray of length 1 is trivially both, both counters start at 1 and the answer is at least 1.
💻 Benchmark Python3 Implementation
class Solution:
def longestMonotonicSubarray(self, nums: List[int]) -> int:
inc = dec = 1 # single-element runs
best = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
inc += 1
dec = 1 # the decreasing run is broken
elif nums[i] < nums[i - 1]:
dec += 1
inc = 1
else:
inc = dec = 1 # equality breaks both
best = max(best, inc, dec)
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass with constant work per element.
💾 Space Complexity
O(1): three counters.
⚠️ Interview Pitfalls & Follow-ups
- Using
>=/<=instead of strict comparisons: equal adjacent elements break monotonicity, so the comparison must be strict. - Forgetting to reset the opposite counter:
[1, 2, 3]would then report a decreasing run that does not exist. - Initialising the counters to 0: a single element is a valid monotonic subarray of length 1.
- Handling equality by only resetting one counter: equality breaks both directions.