⚡Flashcard Drill➔
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

  1. Track two running lengths: inc for the current strictly increasing run and dec for the strictly decreasing run.
  2. Compare each element with its predecessor. If nums[i] > nums[i-1], extend inc and reset dec to 1; if smaller, extend dec and reset inc; if equal, reset both to 1.
  3. The answer is the maximum of both counters over the whole scan.
  4. 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.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

最长的严格递增或递减子数组

给你一个整数数组 nums,返回数组中最长 严格递增 或 严格递减 的非空子数组的长度。约束:1 ≤ nums.length ≤ 50;1 ≤ nums[i] ≤ 50。

核心要点

  • 双计数器一次遍历(标准解) :同时维护以当前位置结尾的「严格递增长度」inc 与「严格递减长度」dec。
  • 递推规则 :若 nums[i] &gt; nums[i-1] 则 inc 加一、dec 重置为 1;若 nums[i] &lt; nums[i-1] 则 dec 加一、inc 重置为 1;若相等则两者都重置为 1。
  • 为什么相等要同时重置 :严格递增/递减都要求相邻元素不等,相等会同时打断两种单调性。
  • 答案取最大值 :每步更新 best = max(best, inc, dec) 。

常见陷阱

  • 相等时只重置一个计数器 :相等会同时打断递增与递减,必须把 inc 与 dec 都重置为 1。这是本题最容易漏的分支。
  • 忘记初始化为 1 :单个元素构成的子数组长度为 1,因此 inc / dec / best 的初值都应为 1(数组至少有一个元素)。
  • 只跟踪递增或只跟踪递减 :必须同时跟踪两者,因为答案可能来自任意一侧。
  • 把「非严格」与「严格」混淆 :题目要求 严格 ,因此相等不算递增。

参考实现

class Solution:
    def longestMonotonicSubarray(self, nums: list[int]) -> int:
        inc = dec = best = 1
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1]:
                inc += 1
                dec = 1
            elif nums[i] < nums[i - 1]:
                dec += 1
                inc = 1
            else:                       # 相等:两种单调性同时中断
                inc = dec = 1
            best = max(best, inc, dec)
        return best