"""Blind 75, Dynamic Programming section (11 problems, plus LC 39 as a bonus)."""
from bisect import bisect_left
from typing import List


def climb_stairs(n: int) -> int:
    """LC 70. ways(n) = ways(n-1) + ways(n-2): Fibonacci with two variables."""
    a, b = 1, 1
    for _ in range(n):
        a, b = b, a + b
    return a


def coin_change(coins: List[int], amount: int) -> int:
    """LC 322. dp[x] = fewest coins for x = 1 + min(dp[x - c]); unbounded knapsack."""
    INF = amount + 1
    dp = [0] + [INF] * amount
    for x in range(1, amount + 1):
        for c in coins:
            if c <= x and dp[x - c] + 1 < dp[x]:
                dp[x] = dp[x - c] + 1
    return dp[amount] if dp[amount] != INF else -1


def length_of_lis(nums: List[int]) -> int:
    """LC 300. Patience sorting: tails[k] = smallest tail of an increasing run of length k+1. O(n log n)."""
    tails: List[int] = []
    for n in nums:
        i = bisect_left(tails, n)
        if i == len(tails):
            tails.append(n)
        else:
            tails[i] = n
    return len(tails)


def longest_common_subsequence(a: str, b: str) -> int:
    """LC 1143. Grid DP: match -> diagonal + 1, else max of left and up. One row of memory."""
    prev = [0] * (len(b) + 1)
    for ch in a:
        cur = [0]
        for j, ch2 in enumerate(b):
            cur.append(prev[j] + 1 if ch == ch2 else max(prev[j + 1], cur[j]))
        prev = cur
    return prev[-1]


def word_break(s: str, word_dict: List[str]) -> bool:
    """LC 139. ok[i] = some word ends at i and ok[i - len(word)] is true."""
    words = set(word_dict)
    lengths = {len(w) for w in words}
    ok = [True] + [False] * len(s)
    for i in range(1, len(s) + 1):
        ok[i] = any(L <= i and ok[i - L] and s[i - L:i] in words for L in lengths)
    return ok[-1]


def combination_sum4(nums: List[int], target: int) -> int:
    """LC 377 (the problem the original Blind 75 link points to). Order matters, so loop target outside, nums inside."""
    dp = [1] + [0] * target
    for x in range(1, target + 1):
        dp[x] = sum(dp[x - n] for n in nums if n <= x)
    return dp[target]


def combination_sum(candidates: List[int], target: int) -> List[List[int]]:
    """LC 39 (bonus: many lists name 'Combination Sum'). Backtrack with a start index so each set appears once."""
    out: List[List[int]] = []
    candidates = sorted(candidates)

    def go(start: int, remaining: int, path: List[int]) -> None:
        if remaining == 0:
            out.append(path[:])
            return
        for i in range(start, len(candidates)):
            c = candidates[i]
            if c > remaining:
                break
            path.append(c)
            go(i, remaining - c, path)
            path.pop()

    go(0, target, [])
    return out


def rob(nums: List[int]) -> int:
    """LC 198. At each house: skip it (keep prev) or rob it (prev2 + value)."""
    prev2 = prev = 0
    for n in nums:
        prev2, prev = prev, max(prev, prev2 + n)
    return prev


def rob_circular(nums: List[int]) -> int:
    """LC 213. First and last are neighbours, so solve House Robber twice: without the first, without the last."""
    if len(nums) == 1:
        return nums[0]
    return max(rob(nums[1:]), rob(nums[:-1]))


def num_decodings(s: str) -> int:
    """LC 91. Like stairs: take one digit if it is not '0', two digits if they form 10..26."""
    two_back, one_back = 1, 1 if s[0] != "0" else 0  # ways for s[:i-1] and s[:i]
    for i in range(1, len(s)):
        cur = one_back if s[i] != "0" else 0
        if 10 <= int(s[i - 1:i + 1]) <= 26:
            cur += two_back
        two_back, one_back = one_back, cur
    return one_back


def unique_paths(m: int, n: int) -> int:
    """LC 62. Each cell = cell above + cell to the left; one row suffices."""
    row = [1] * n
    for _ in range(1, m):
        for j in range(1, n):
            row[j] += row[j - 1]
    return row[-1]


def can_jump(nums: List[int]) -> bool:
    """LC 55. Greedy: track the farthest index reachable; fail if you stand beyond it."""
    reach = 0
    for i, n in enumerate(nums):
        if i > reach:
            return False
        reach = max(reach, i + n)
    return True
