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

LeetCode 3904: Smallest Stable Index II

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

基本資料
#

難易度: medium 第一次嘗試: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 3903。

我的解法
#

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 3719: Longest Balanced Subarray I
·1 分鐘
LeetCode Medium Hash-Table Prefix-Sum Segment-Tree Array
LeetCode 3719 解題筆記:n 只有 1500,固定左端點往右擴,用兩個集合增量維護不同的奇數和偶數
LeetCode 930: Binary Subarrays With Sum
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 930 解題筆記:「和剛好是 goal」= 「和最多 goal」−「和最多 goal - 1」;或用前綴和 + 雜湊表
LeetCode 1838: Frequency of the Most Frequent Element
·1 分鐘
LeetCode Medium Sliding-Window Sorting Greedy Prefix-Sum Binary-Search Array
LeetCode 1838 解題筆記:排序後,把視窗裡的數都加到 nums[right] 的花費是 nums[right] × 長度 − 視窗總和;花費 > k 就縮左邊
LeetCode 2271: Maximum White Tiles Covered by a Carpet
·1 分鐘
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 2271 解題筆記:地毯的左端放在某段白磚的起點一定不會更差;排序後用雙指針,完整蓋住的段累加,最後一段只算部分
LeetCode 2875: Minimum Size Subarray in Infinite Array
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 2875 解題筆記:先拿掉 target // sum 個完整週期,剩下的餘數比一整圈小,一定能在兩份 nums 接起來的陣列裡用滑動視窗找到
LeetCode 3413: Maximum Coins From K Consecutive Bags
·2 分鐘
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 3413 解題筆記:最佳的 k 個袋子,一定有一端對齊某段的端點;分別算「左端對齊段的起點」和「右端對齊段的終點」(鏡像後重用同一個函式)