The Candy problem involves distributing candies to children standing in a line such that:
The goal is to determine the minimum number of candies required to satisfy these conditions.
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1);
// Left-to-right pass
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// Right-to-left pass
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
// Calculate the total candies
int totalCandies = 0;
for (int candy : candies) {
totalCandies += candy;
}
return totalCandies;
}
}
For a detailed explanation, watch this video: Candy Problem Explanation by NeetCode IO
O(N)
, where N
is the number of children.O(N)
, for the candies array.Input: ratings = [1,0,2]
Output: 5
Explanation:
- Give 2 candies to the child with a rating of 2.
- Give 1 candy to the child with a rating of 0.
- Give 2 candies to the child with a rating of 1.
- Total candies = 2 + 1 + 2 = 5.