def best_prefix_recursive(rewards: list[int], count: int) -> int:
    """Return the best nonadjacent reward from a prefix by recursion.

    Args:
        rewards: Integer rewards; selecting no position is allowed.
        count: Prefix length between zero and len(rewards).

    Returns:
        The greatest sum from nonadjacent positions in the prefix.
    """
    if count == 0:
        return 0
    if count == 1:
        return max(0, rewards[0])
    skip = best_prefix_recursive(rewards, count - 1)
    take = rewards[count - 1] + best_prefix_recursive(rewards, count - 2)
    return max(skip, take)


rewards = [4, 9, 3, 7, 6]
print("Recursive best reward:", best_prefix_recursive(rewards, len(rewards)))

def reward_table(rewards: list[int]) -> list[int]:
    """Compute the best nonadjacent reward for every prefix.

    Args:
        rewards: Integer rewards; selecting no position is allowed.

    Returns:
        A list where entry i is the optimum for the first i positions.
    """
    table = [0] * (len(rewards) + 1)
    for count in range(1, len(rewards) + 1):
        skip = table[count - 1]
        previous = table[count - 2] if count >= 2 else 0
        take = previous + rewards[count - 1]
        table[count] = max(skip, take)
    return table


table = reward_table(rewards)
print("Prefix table:", table)
print("prefix | skip | take | best")
for count in range(1, len(rewards) + 1):
    skip = table[count - 1]
    previous = table[count - 2] if count >= 2 else 0
    take = previous + rewards[count - 1]
    print(count, skip, take, table[count], sep=" | ")
print("Tabulated best reward:", table[-1])

def best_reward(rewards: list[int]) -> int:
    """Return the best nonadjacent reward with constant auxiliary storage.

    Args:
        rewards: Integer rewards; selecting no position is allowed.

    Returns:
        The greatest sum from nonadjacent positions.
    """
    two_back = 0
    one_back = 0
    for reward in rewards:
        current = max(one_back, two_back + reward)
        two_back, one_back = one_back, current
    return one_back


print("Constant-space best reward:", best_reward(rewards))
for case in ([], [7], [-3, -1], [5, 1, 5], [4, 9, 3, 7, 6]):
    expected = best_prefix_recursive(case, len(case))
    assert reward_table(case)[-1] == expected
    assert best_reward(case) == expected
print("The empty, singleton, negative, and separated-choice cases pass.")

def cached_prefix_reward(
    rewards: list[int], count: int, memo: dict[int, int]
) -> int:
    """Evaluate a prefix using a cache owned by one reward problem.

    Args:
        rewards: Fixed integer rewards that remain unchanged during the call.
        count: Prefix length between zero and len(rewards).
        memo: Correct cached answers for this same reward sequence.

    Returns:
        The greatest reward from nonadjacent positions in the prefix.
    """
    if count in memo:
        return memo[count]
    if count == 0:
        answer = 0
    elif count == 1:
        answer = max(0, rewards[0])
    else:
        skip = cached_prefix_reward(rewards, count - 1, memo)
        take = rewards[count - 1] + cached_prefix_reward(
            rewards, count - 2, memo
        )
        answer = max(skip, take)
    memo[count] = answer
    return answer


def best_reward_memoized(rewards: list[int]) -> int:
    """Return an optimum using a fresh recursive cache for this input.

    Args:
        rewards: Integer rewards; selecting nothing is permitted.

    Returns:
        The greatest sum obtainable without adjacent selected positions.
    """
    return cached_prefix_reward(rewards, len(rewards), {})


prefix_cache = {}
print("Memoized optimum:", cached_prefix_reward(
    rewards, len(rewards), prefix_cache
))
print("Completed states:", sorted(prefix_cache.items()))
print("A separate problem:", best_reward_memoized([1, 20, 1]))
print("Original problem again:", best_reward_memoized(rewards))

def best_reward_selection(rewards: list[int]) -> tuple[int, list[int]]:
    """Return an optimal total and one compatible selection of positions.

    Args:
        rewards: Integer rewards in input order. The input is unchanged.

    Returns:
        The maximum total and selected indices in increasing order. Ties
        prefer skipping the later position, and selecting nothing is valid.
    """
    table = reward_table(rewards)
    selected = []
    count = len(rewards)
    while count > 0:
        if table[count] == table[count - 1]:
            count -= 1
        else:
            selected.append(count - 1)
            count -= 2
    selected.reverse()
    return table[-1], selected


selection_total, selection_indices = best_reward_selection(rewards)
print("Optimal total:", selection_total)
print("Selected positions:", selection_indices)
print("Selected rewards:", [rewards[index] for index in selection_indices])
assert sum(rewards[index] for index in selection_indices) == selection_total
assert all(
    right - left > 1
    for left, right in zip(selection_indices, selection_indices[1:])
)
assert best_reward_selection([]) == (0, [])
assert best_reward_selection([-2, -1]) == (0, [])
assert best_reward_selection([5, 5]) == (5, [0])
print("Reconstructed totals, nonadjacency, empty inputs, and ties pass.")
