Back to Practice
#0301

Candy

HardDSA40 min25 XP

Problem

Each child must get at least one candy. Children with higher rating than an adjacent neighbor must get more candies than that neighbor. Return the minimum total candies.

Why This Matters

Candy is a two-pass greedy problem where left and right constraints must both be satisfied.

Function Signature

def candy(ratings):

Examples

Example 1
Inputratings = [1,0,2]
Output5

Candies [2,1,2] satisfy both neighbor constraints.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Valley
Input[1,0,2]
Expected5

The middle child gets one candy; both neighbors get more.

Plateau
Input[1,2,2]
Expected4

Equal ratings do not require more candy.

Hidden Test Categories
strictly increasingstrictly decreasingsingle child