"""Stage 14: 1-D Dynamic Programming (problems 119-130)."""
from __future__ import annotations

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 min_cost_climbing_stairs(cost: List[int]) -> int:
    """LC 746. Cost to stand on step i = cost[i] + min of the two steps below."""
    a, b = 0, 0  # cheapest cost to reach the two previous positions
    for c in cost:
        a, b = b, c + min(a, b)
    return min(a, b)


def rob(nums: List[int]) -> int:
    """LC 198. best(i) = max(best(i-1), best(i-2) + nums[i])."""
    skip, take = 0, 0
    for x in nums:
        skip, take = max(skip, take), skip + x
    return max(skip, take)


def rob_circular(nums: List[int]) -> int:
    """LC 213. The first and last houses cannot both be robbed: solve two linear ranges."""
    if len(nums) == 1:
        return nums[0]
    return max(rob(nums[1:]), rob(nums[:-1]))


def longest_palindrome(s: str) -> str:
    """LC 5. Expand around each of the 2n-1 centres."""
    best = (0, 0)
    for center in range(2 * len(s) - 1):
        lo, hi = center // 2, center // 2 + center % 2
        while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
            lo, hi = lo - 1, hi + 1
        if hi - lo - 1 > best[1] - best[0]:
            best = (lo + 1, hi)
    return s[best[0]:best[1]]


def count_substrings(s: str) -> int:
    """LC 647. Same centre expansion; every successful step is one more palindrome."""
    count = 0
    for center in range(2 * len(s) - 1):
        lo, hi = center // 2, center // 2 + center % 2
        while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
            count += 1
            lo, hi = lo - 1, hi + 1
    return count


def num_decodings(s: str) -> int:
    """LC 91. ways(i) = ways(i-1) if s[i] != '0' + ways(i-2) if s[i-1:i+1] in 10..26."""
    prev2, prev1 = 1, 1 if s and s[0] != "0" else 0
    for i in range(1, len(s)):
        cur = prev1 if s[i] != "0" else 0
        if 10 <= int(s[i - 1:i + 1]) <= 26:
            cur += prev2
        prev2, prev1 = prev1, cur
    return prev1 if s else 0


def coin_change(coins: List[int], amount: int) -> int:
    """LC 322. Unbounded knapsack for the minimum count; inf marks unreachable."""
    best = [0] + [float("inf")] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1
    return -1 if best[amount] == float("inf") else int(best[amount])


def max_product(nums: List[int]) -> int:
    """LC 152. Track both the max and min product ending here: a negative flips them."""
    best = hi = lo = nums[0]
    for x in nums[1:]:
        candidates = (x, hi * x, lo * x)
        hi, lo = max(candidates), min(candidates)
        best = max(best, hi)
    return best


def word_break(s: str, word_dict: List[str]) -> bool:
    """LC 139. ok[i] is true when some word ends at i and ok[start of that 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 length_of_lis(nums: List[int]) -> int:
    """LC 300. Patience sorting: tails[k] = smallest tail of an increasing run of length k+1."""
    import bisect

    tails: List[int] = []
    for x in nums:
        i = bisect.bisect_left(tails, x)
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)


def can_partition(nums: List[int]) -> bool:
    """LC 416. Subset sum to total/2; a set of reachable sums (or a bitmask) is enough."""
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    reachable = 1  # bit i set means sum i is reachable
    for x in nums:
        reachable |= reachable << x
    return bool(reachable >> target & 1)
