KatInterview

Fewest Badges for a Row of Scored Players

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsgreedyarraytwo-pass

Last updated

Greedy two-pass array problem: assign the minimum total badges so each player gets at least one and any player scoring higher than an adjacent player gets strictly more badges.

Badges for a Row of Players

A line of players has just finished a contest, and each player has an integer score. You must hand out badges to the players following these rules:

  1. Every player receives at least one badge.
  2. If a player's score is strictly greater than the score of a player standing directly next to them (on either side), that player must receive strictly more badges than that neighbor.

Players with equal scores place no restriction on each other: they may receive the same number of badges or different numbers.

Write a function that returns the smallest total number of badges that can be handed out while obeying both rules.

If the list of scores is empty, return 0.

Input

  • scores: a list of integers, where scores[i] is the score of the player at position i.

Output

  • An integer: the minimum total number of badges.

Constraints

  • 0 <= len(scores) <= 20000
  • 0 <= scores[i] <= 20000
  • Only the strict comparisons with immediate left and right neighbors matter.
  • An empty list gives 0; a single player gives 1.

Examples

Example 1

Input: min_badges([1, 0, 2])

Output: 5

Example 2

Input: min_badges([1, 2, 2])

Output: 4

Hints

Hint 1

Each player has up to two constraints, one from the left neighbor and one from the right. Try handling the two directions separately instead of in one pass.

Hint 2

Start everyone with one badge. Sweep left to right and give a player one more than the left neighbor whenever their score is strictly higher than that neighbor's.

Hint 3

Sweep right to left in the same way, but take the maximum of the current value and the right-derived requirement so the left-side guarantee from the first sweep is not lost. Then sum the array.