Problem
Problem page: https://leetcode.com/problems/candy/
Topics: Greedy
Difficulty: Hard
There are N children standing in a line. Each child is assigned a rating value.
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.
What is the minimum candies you must give?
Analysis
I use a greedy algorithm. I start with an array of size N filled with 1s, since each child gets at least one candy. Then I make two greedy passes:
- First I go from left to right. If a child's rating is higher than their left neighbor's, I give them one more candy than their left neighbor.
- Next I go from right to left. If a child's rating is higher than their right neighbor's, they need at least one more candy than their right neighbor. Of course, if they already have more candies than their right neighbor, I leave their count alone.
(I wonder how to prove that the greedy algorithm gives an optimal solution.)
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-candy/
