"""Week 14: Dynamic programming foundations. State, transition, base case, order."""
from __future__ import annotations

from functools import lru_cache
from typing import List


def climb_stairs(n: int, steps=(1, 2)) -> int:
    """Number of ways to reach step n using the allowed step sizes."""
    ways = [1] + [0] * n
    for i in range(1, n + 1):
        ways[i] = sum(ways[i - s] for s in steps if s <= i)
    return ways[n]


def min_coins(coins: List[int], amount: int) -> int:
    """Fewest coins for amount, or -1. Unbounded knapsack."""
    INF = float("inf")
    best = [0] + [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] == INF else int(best[amount])


def count_coin_combinations(coins: List[int], amount: int) -> int:
    """Number of combinations (order does not matter): coins in the outer loop."""
    ways = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            ways[a] += ways[a - c]
    return ways[amount]


def knapsack_01(weights: List[int], values: List[int], capacity: int) -> int:
    """Each item at most once: iterate capacity downwards so an item is not reused."""
    best = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        for cap in range(capacity, w - 1, -1):
            best[cap] = max(best[cap], best[cap - w] + v)
    return best[capacity]


def house_robber(nums: List[int]) -> int:
    take, skip = 0, 0
    for x in nums:
        take, skip = skip + x, max(skip, take)
    return max(take, skip)


def max_subarray(nums: List[int]) -> int:
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best


def grid_paths(grid: List[List[int]]) -> int:
    """Paths from top-left to bottom-right moving right/down; cells with 1 are blocked."""
    rows, cols = len(grid), len(grid[0])
    dp = [0] * cols
    dp[0] = 1 if grid[0][0] == 0 else 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1:
                dp[c] = 0
            elif c > 0:
                dp[c] += dp[c - 1]
    return dp[-1]


def min_path_sum(grid: List[List[int]]) -> int:
    rows, cols = len(grid), len(grid[0])
    dp = [float("inf")] * cols
    dp[0] = 0
    for r in range(rows):
        for c in range(cols):
            left = dp[c - 1] if c > 0 else float("inf")
            dp[c] = grid[r][c] + min(dp[c], left)
    return int(dp[-1])


def rod_cutting(prices: List[int], length: int) -> int:
    """prices[i] is the price of a piece of length i + 1."""

    @lru_cache(maxsize=None)
    def best(n: int) -> int:
        if n == 0:
            return 0
        return max(prices[i] + best(n - i - 1) for i in range(min(n, len(prices))))

    return best(length)
