"""Stage 3: Sliding Window (problems 21-28)."""
from __future__ import annotations

from collections import Counter, deque
from typing import List


def max_profit(prices: List[int]) -> int:
    """LC 121. Track the cheapest price so far; profit = today - cheapest."""
    cheapest, best = float("inf"), 0
    for p in prices:
        cheapest = min(cheapest, p)
        best = max(best, p - cheapest)
    return best


def length_of_longest_substring(s: str) -> int:
    """LC 3. Remember each char's last index; jump the left edge past a repeat."""
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        if last.get(ch, -1) >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best


def character_replacement(s: str, k: int) -> int:
    """LC 424. Window is valid while length - (count of most common char) <= k."""
    counts = Counter()
    left = top = best = 0
    for right, ch in enumerate(s):
        counts[ch] += 1
        top = max(top, counts[ch])  # never needs to decrease: only a larger top can improve the answer
        while right - left + 1 - top > k:
            counts[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best


def check_inclusion(s1: str, s2: str) -> bool:
    """LC 567. Fixed-size window; compare 26-count arrays as it slides."""
    if len(s1) > len(s2):
        return False
    need, window = [0] * 26, [0] * 26
    for a, b in zip(s1, s2):
        need[ord(a) - 97] += 1
        window[ord(b) - 97] += 1
    if need == window:
        return True
    for i in range(len(s1), len(s2)):
        window[ord(s2[i]) - 97] += 1
        window[ord(s2[i - len(s1)]) - 97] -= 1
        if need == window:
            return True
    return False


def min_window(s: str, t: str) -> str:
    """LC 76. Expand right until all needed chars are covered, then shrink left while still covered."""
    need = Counter(t)
    missing = len(t)
    left = 0
    best = (float("inf"), 0, 0)
    for right, ch in enumerate(s):
        if need[ch] > 0:
            missing -= 1
        need[ch] -= 1
        while missing == 0:
            if right - left + 1 < best[0]:
                best = (right - left + 1, left, right + 1)
            need[s[left]] += 1
            if need[s[left]] > 0:
                missing += 1
            left += 1
    return s[best[1]:best[2]] if best[0] != float("inf") else ""


def max_sliding_window(nums: List[int], k: int) -> List[int]:
    """LC 239. Monotonic decreasing deque of indices; front is the window max."""
    dq: deque = deque()
    out = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out


def min_subarray_len(target: int, nums: List[int]) -> int:
    """LC 209. All positive numbers: shrink from the left while the sum still reaches target."""
    left = total = 0
    best = float("inf")
    for right, x in enumerate(nums):
        total += x
        while total >= target:
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == float("inf") else int(best)


def find_anagrams(s: str, p: str) -> List[int]:
    """LC 438. Same fixed window as LC 567, but collect every matching start index."""
    if len(p) > len(s):
        return []
    need, window = Counter(p), Counter(s[: len(p)])
    out = [0] if need == window else []
    for i in range(len(p), len(s)):
        window[s[i]] += 1
        old = s[i - len(p)]
        window[old] -= 1
        if window[old] == 0:
            del window[old]
        if window == need:
            out.append(i - len(p) + 1)
    return out
