Timeline
timeline
2025-10-20
init
greedy
Title:
Imagine ratings form a continuous mountain range. Initially we set all to 1, which is flat ground. Scanning from left to right handles all uphill elements, scanning from right to left handles downhill elements. For the boundary between uphill and downhill, we need to take the maximum of the left requirement and right requirement plus 1, so that it satisfies both uphill and downhill.
Initialize by giving each person one candy.
🍬 Step 1: Left to Right
Ensure that children with higher ratings than the left get more candies:
1 | if (ratings[i] > ratings[i-1]) |
🍬 Step 2: Right to Left
Ensure that children with higher ratings than the right get more candies, while taking the maximum with the existing value (to avoid breaking the left-to-right rule):
1 | if (ratings[i] > ratings[i+1]) |
- Uphill from left to right, because the right needs to reference the left.
- Downhill from right to left, because the left side needs to reference the right side.
Code:
1 |
|
