"""Pattern 19: Dynamic programming.

Recipe: (1) define the state, e.g. dp[i] = answer for the first i items;
(2) write the transition from smaller states; (3) set base cases; (4) pick
an order so every state is computed before it is used; (5) shrink memory if
only the last row or two are needed.
"""

from bisect import bisect_left


def climb_stairs(n: int) -> int:
    """dp[i] = dp[i-1] + dp[i-2]; only two values are needed."""
    a, b = 1, 1
    for _ in range(n):
        a, b = b, a + b
    return a


def rob(nums: list[int]) -> int:
    """House robber: best = max(skip this house, take it + best two back)."""
    prev2 = prev1 = 0
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)
    return prev1


def coin_change(coins: list[int], amount: int) -> int:
    """Unbounded knapsack style: fewest coins for each amount, -1 if impossible."""
    INF = amount + 1
    dp = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a:
                dp[a] = min(dp[a], dp[a - c] + 1)
    return dp[amount] if dp[amount] != INF else -1


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


def longest_common_subsequence(a: str, b: str) -> int:
    """2-D grid DP kept to one row plus a saved diagonal."""
    dp = [0] * (len(b) + 1)
    for ch in a:
        diagonal = 0
        for j, other in enumerate(b, start=1):
            above = dp[j]
            dp[j] = diagonal + 1 if ch == other else max(dp[j], dp[j - 1])
            diagonal = above
    return dp[-1]


def min_distance(a: str, b: str) -> int:
    """Edit distance: insert, delete or replace one character per step."""
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, start=1):
        cur = [i] + [0] * len(b)
        for j, cb in enumerate(b, start=1):
            cur[j] = prev[j - 1] if ca == cb else 1 + min(prev[j - 1], prev[j], cur[j - 1])
        prev = cur
    return prev[-1]


def unique_paths(m: int, n: int) -> int:
    """Grid paths moving only right/down: each cell = above + left."""
    row = [1] * n
    for _ in range(1, m):
        for j in range(1, n):
            row[j] += row[j - 1]
    return row[-1]


def can_partition(nums: list[int]) -> bool:
    """0/1 subset sum to half the total; iterate sums downwards to use each item once."""
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    reachable = [True] + [False] * target
    for x in nums:
        for s in range(target, x - 1, -1):
            reachable[s] = reachable[s] or reachable[s - x]
    return reachable[target]


def word_break(s: str, words: list[str]) -> bool:
    """dp[i] = s[:i] can be segmented."""
    vocab = set(words)
    dp = [True] + [False] * len(s)
    for i in range(1, len(s) + 1):
        dp[i] = any(dp[j] and s[j:i] in vocab for j in range(i))
    return dp[-1]
