Python coding

Fewest tokens for a scored row

People stand in a row and scores[i] is the score of the person at position i. Hand out reward tokens so that everyone gets at least one, and anyone with a strictly higher score than a person directly next to them gets more tokens than that neighbor. Return the minimum total number of tokens.

Neighbors with equal scores put no constraint on each other. scores may be empty.

Besides the tests, one large input (2,500 people) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • min_tokens([3,5,5]) → 4
  • min_tokens([5,3,1]) → 6
  • min_tokens([2,4,3,1]) → 7
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Split the rule in two: more than a lower-scoring left neighbor, and more than a lower-scoring right neighbor. Each half alone is easy to satisfy greedily.

Hint 2

Start everyone at 1. Sweep left to right: a higher score than the left neighbor gets that neighbor's tokens plus 1. Then sweep right to left for the right neighbor.

Hint 3

The trap is in the second sweep: take max(current, right + 1), not just right + 1, or you undo what the first sweep fixed. A single pass fails on long descending runs.

Solution and why it works
pythonO(n) · O(n)
def min_tokens(scores: list[int]) -> int:
    n = len(scores)
    tokens = [1] * n
    for i in range(1, n):                # more than a lower-scoring left neighbor
        if scores[i] > scores[i - 1]:
            tokens[i] = tokens[i - 1] + 1
    for i in range(n - 2, -1, -1):       # more than a lower-scoring right neighbor
        if scores[i] > scores[i + 1]:
            tokens[i] = max(tokens[i], tokens[i + 1] + 1)
    return sum(tokens)

Each person needs 1 plus the number of consecutive rises leading up to them, counted from the left and from the right. The left-to-right sweep counts the first, the right-to-left sweep the second, and max keeps the larger, so both neighbors are satisfied with nothing to spare. One pass cannot work: in [3, 2, 1] the first person's tokens depend on how long the descent after them is. Equal scores impose nothing, so [2, 2] needs just 2.