Candy
The problem
A line of N kids is standing there. The rating values listed in the integer array ratings are assigned to each kid.
These kids are receiving candy, according to the following criteria:
-
There must be at least one candy for every child.
-
Kids whose scores are higher than their neighbours receive more candies than their neighbours.
Return the minimum number of candies needed to distribute among children.
Input : ratings = [1, 0, 5]
Output : 5
Explanation : The distribution of candies will be 2 , 1 , 2 to first , second , third child respectively.
Input : ratings = [1, 2, 2]
Output : 4
Explanation : The distribution of candies will be 1 , 2 , 1 to first , second , third child respectively. The third gets only 1 candy because it satisfy above two criteria.
Input : ratings = [1, 2, 1, 4, 5]
- 1 <= n <= 104
- 0 <= ratings[i] <= 105
cpp
class Solution {
public:
int candy(vector<int>& ratings) {
//your code goes here
}
};java
class Solution {
public int candy(int[] ratings) {
//your code goes here
}
}python
class Solution:
def candy(self, ratings):
#your code goes herejavascript
class Solution {
candy(ratings) {
//your code goes here
}
}csharp
public class Solution {
public int Candy(int[] ratings) {
}
}go
func candy(ratings []int) int {
}Stuck? Show a way to structure it+
- 01Initialize all candies to one
- 02Satisfy rising slopes from the left
- 03Satisfy descending slopes from the right with max
- 04Sum after both constraints are met
Reference answer
Then expect these follow-ups
Can this be solved in O(1) extra space?
Tests: complexity analysis
Why does taking max satisfy both neighbors?
Tests: correctness reasoning
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question