InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Greedy

Candy

hard Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug