↓快轉到主要內容
  1. LeetCode/

LeetCode 3903: Smallest Stable Index I

·1 分鐘· ·
LeetCode Easy Prefix-Sum Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2026-04-19

  • 提交紀錄:Accepted(一次通過)

解題思路
#

每個 index 的分數是 max(nums[0..i]) - min(nums[i..n-1]),兩邊各掃一次(Prefix Sum 模板二):

  • 後綴最小值從右往左先建好。
  • 前綴最大值從左往右邊掃邊更新,第一個分數 <= k 的就回傳。

這題的 I 和 II 只差在長度上限(I 是 100、II 是 10^5),我兩題用的是同一份 O(n) 程式;I 的範圍小,每個位置直接算 max 和 min 的 O(n²) 也會過。另一題見 LeetCode 3904。

我的解法
#

class Solution:
    def firstStableIndex(self, nums: List[int], k: int) -> int:
        n = len(nums)
        suf_min = nums[:]
        for i in range(n - 2, -1, -1):
            suf_min[i] = min(suf_min[i + 1], nums[i])
        pre_max = -inf
        for i, x in enumerate(nums):
            pre_max = max(pre_max, x)
            if pre_max - suf_min[i] <= k:
                return i
        return -1

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 兩個區間都包含 i 自己。

面試口說整理
#

分數是左邊到 i 的最大值減右邊從 i 開始的最小值。我先從右往左建後綴最小值,再從左往右維護前綴最大值,第一個差 <= k 的位置就是答案。時間 O(n)。

相關文章

LeetCode 1413: Minimum Value to Get Positive Step by Step Sum
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1413 解題筆記:起始值加上每個前綴和都要 >= 1,所以起始值是 max(1, 1 - 最小前綴和)
LeetCode 1480: Running Sum of 1d Array
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1480 解題筆記:前綴和的定義,每一格加上前一格
LeetCode 1732: Find the Highest Altitude
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1732 解題筆記:海拔就是 gain 的前綴和,起點是 0,取最大值
LeetCode 1991: Find the Middle Index in Array
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1991 解題筆記:先算總和,掃描時維護左邊的和,右邊的和是 total - left - nums[i]
LeetCode 3904: Smallest Stable Index II
·1 分鐘
LeetCode Medium Prefix-Sum Array
LeetCode 3904 解題筆記:前綴最大值減後綴最小值 <= k 的第一個 index;後綴最小值先從右往左建好
LeetCode 3898: Find the Degree of Each Vertex
·1 分鐘
LeetCode Easy Graph Matrix Array
LeetCode 3898 解題筆記:鄰接矩陣第 i 列的 1 的個數就是頂點 i 的度數