MEDIUM Greedy
135. Candy
๐ Problem
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: - Each child must have at least one candy. - Children with a higher rating get more candies than their neighbors. Return the minimum number of candies you need to have to distribute the candies to the children.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Greedy reasoning pattern
๐ก Approach
- โ Give each child 1 candy initially
- โ Left to right pass: give more candy if rating > left neighbor
- โ Right to left pass: give more candy if rating > right neighbor
- โ Use max of both passes for each child
- โ Time: O(n), Space: O(n)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขGive each child 1 candy initially
- โขLeft to right pass: give more candy if rating > left neighbor
- โขRight to left pass: give more candy if rating > right neighbor
Common Pitfalls
- โขUse max of both passes for each child
- โขTime: O(n), Space: O(n)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
candy([1,0,2]); Expected:
5 Test Case 2
Not run Input:
candy([1,2,2]); Expected:
4 Test Case 3
Not run Input:
candy([1,3,2,2,1]); Expected:
7 ๐ Code Editor
๐ค Output