公開記念セール すべてのパスが 50% オフ

プランを見る

Start from the invariant.

全 66 件中 66 件のテンプレート

Sliding window

Sliding window

Maintain a valid contiguous interval.

Interview essentials
Free pattern

When to use it

Find the longest contiguous array segment whose sum is at most a limit. Every value must be nonnegative.

What stays true

After shrinking, sum equals the total in [left, right] and is at most the limit. Removing another left value cannot produce a longer valid segment ending here.

Time
O(n)
Extra space
O(1)
sliding_window.py
def longest_window(nums: list[int], limit: int) -> int:
    """Longest segment with sum <= limit; nums must be nonnegative."""
    if limit < 0:
        return 0
    left = total = best = 0
    for right, value in enumerate(nums):
        total += value
        while total > limit:
            total -= nums[left]
            left += 1
        best = max(best, right - left + 1)
    return best

Functions and classes only. Call them from your judge’s required entry point.

nums = [2, 1, 3, 1], limit = 4 → 2. Both [2, 1] and [3, 1] have length 2.

Keep the sum at most 4

Extend

  1. 2(active)
  2. 1(active)
  3. 3
  4. 1

[2, 1] sums to 3 and has length 2.

1 / 4

Templates

Esc
↑↓移動 ↵開く Ctrl↵新しいタブ >操作 ?ショートカット

キーボードショートカット

どこでも

検索を開く
CtrlKまたは /
この一覧を表示
?
ウィンドウやメニューを閉じる
Esc

検索中

結果を移動
↑または ↓
結果を開く
↵
新しいタブで開く(問題はジャッジで開く)
Ctrl↵
操作だけを表示
>
絞り込みを解除
⌫

移動

学習
Gの次にL
練習
Gの次にP
ランクテスト
Gの次にA
システム設計
Gの次にS
企業
Gの次にC
マイプロフィール
Gの次にM
今日のクエスト
Gの次にT
ホーム
Gの次にH

バグを報告

ページ