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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit