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

LeetCode 2958: Length of Longest Subarray With at Most K Frequency

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

基本資料
#

難易度: medium 第一次嘗試:2026-01-10

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

解題思路
#

跟 LeetCode 3090 同一個模板,只是上限從 2 變成 k、字元換成整數。

右邊界加入 x 後,只有 x 可能超過 k 次,縮左邊直到它回到 k 次。

我的解法
#

class Solution:
    def maxSubarrayLength(self, nums: List[int], k: int) -> int:
        cnt = Counter()
        left = best = 0
        for right, x in enumerate(nums):
            cnt[x] += 1
            while cnt[x] > k:
                cnt[nums[left]] -= 1
                left += 1
            best = max(best, right - left + 1)
        return best

複雜度
#

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

要特別避免的錯誤
#

  • 縮視窗的條件寫成檢查左邊的元素:要看的是剛加入的 x。

面試口說整理
#

求最長的滑動視窗,每個數字最多 k 次。右邊加入 x 之後,只有 x 可能超過,所以縮左邊直到 x 回到 k 次,記錄最長長度。時間 O(n)。

相關文章

LeetCode 2653: Sliding Subarray Beauty
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2653 解題筆記:值域只有 -50 到 50,固定視窗用計數陣列維護,每個視窗從 -50 往上累加找第 x 小的負數
LeetCode 3795: Minimum Subarray Length With Distinct Sum At Least K
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 3795 解題筆記:求最短的可變視窗;同一個值只算一次,記錄每個值最後出現的位置,左邊界移出的是最後一次出現才扣掉
LeetCode 2461: Maximum Sum of Distinct Subarrays With Length K
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2461 解題筆記:固定長度 k 的視窗,不同值的個數剛好等於 k 才代表全部不重複
LeetCode 3679: Minimum Discards to Balance Inventory
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 解題筆記:規則已經決定哪些要丟,直接模擬;長度 w 的視窗只計算「留下來」的到貨,被丟掉的離開視窗時不能再扣
LeetCode 2841: Maximum Sum of Almost Unique Subarray
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2841 解題筆記:固定長度 k 的視窗,維護總和與計數雜湊表;不同值的個數就是雜湊表的大小,數量歸零要刪 key
LeetCode 1248: Count Number of Nice Subarrays
·2 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 1248 解題筆記:「剛好 k 個奇數」不單調,改成「最多 k 個」減「最多 k - 1 個」;或用前綴和 + 雜湊表