InterviewPrepKit

Home / Coding / Greedy

Candy

hard Original ↗
Solving tips
  • Decompose the two-sided constraint into two independent one-directional passes: a left-to-right sweep enforces the left-neighbor rule, a right-to-left sweep the right-neighbor rule.
  • Each child needs the MAX of the two sweeps' demands (not the sum), which satisfies both neighbors at once for the minimum total; O(n) time, O(n) space.
  • Start everyone at a floor of 1; equal ratings impose no constraint so a tie resets toward 1 rather than carrying the run forward.
  • Pitfall: using sum instead of max over-allocates; a slope-counting one-pass variant achieves O(1) space via arithmetic series, needing the peak adjustment when a descent grows past the preceding ascent.

Problem

n children stand in a row, and each has a rating given by ratings[i]. You must hand out candies subject to two rules:

  1. Every child gets at least one candy.
  2. A child with a strictly higher rating than an adjacent child (immediate left or right neighbor) must receive strictly more candies than that neighbor.

Return the minimum total number of candies that satisfies both rules. (Children with equal ratings have no constraint relative to each other.)

Examples

  • ratings = [1, 0, 2]5 — candies [2, 1, 2]: the middle child (rating 0) gets the minimum 1; both neighbors outrank it so they get 2.
  • ratings = [1, 2, 2]4 — candies [1, 2, 1]: the second child outranks the first (2 > 1). The third ties the second, so it may drop back to 1.
  • ratings = [1, 3, 4, 5, 2]11 — candies [1, 2, 3, 4, 1]: the long ascending run forces 1,2,3,4, then the final child (rating 2 < 5) resets to 1.

Constraints

  • 1 <= n == len(ratings) <= 2 * 10^4
  • 0 <= ratings[i] <= 2 * 10^4
  • The 2 * 10^4 bound expects O(n) (or O(n) with O(1) extra space); an O(n^2) relaxation loop is borderline but wasteful.

Think about it first

Hint 1 Only adjacent comparisons matter. A child's candy count is pinned down by how it compares to its left neighbor and to its right neighbor — two separate constraints.
Hint 2 Handle the two directions independently. First sweep left to right enforcing "higher than left neighbor ⇒ more candy." Then sweep right to left enforcing "higher than right neighbor ⇒ more candy."
Hint 3 For each child, take the maximum of what the two sweeps demand — that single value satisfies both neighbors at once, and taking the max (rather than the sum) keeps the total minimal. Every child still starts from a floor of 1.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.