Candy
Problem Statement
There are n children standing in a line, and each child has a rating. You want to give out candy so that:
- every child gets at least one candy, and
- a child with a higher rating than a neighbour gets more candy than that neighbour.
Return the smallest total number of candies that meets both rules.
An array ratings, where ratings[i] is the rating of child i.
The minimum total number of candies.
Give 2, 1 and 2 candies. Child 0 and child 2 both have higher ratings than child 1, so each gets more than child 1.
Give 1, 2 and 1 candies. Child 1 is rated higher than child 0, so it gets more. Child 2 has the same rating as child 1, so the rule does not apply and 1 candy is enough.
- • 1 ≤ n ≤ 5 · 10^4
- • n equals the length of `ratings`.
- • 0 ≤ ratings[i] ≤ 5 · 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Start everyone at 1 and repeat sweeps until no neighbour rule is broken
One pass for the left rule, one for the right rule; each child takes the larger value
Give every child 1 candy. Sweep the line and check each pair. If a child who is rated higher has no more candy than a lower-rated neighbour, raise that child to one more than the neighbour. Repeat full sweeps until one sweep changes nothing. Then add up all the candy.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Greedy translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.