Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created June 2, 2025 16:18
Show Gist options
  • Save tatsuyax25/770b7fd671ab77d8f124cc47faeccb09 to your computer and use it in GitHub Desktop.
Save tatsuyax25/770b7fd671ab77d8f124cc47faeccb09 to your computer and use it in GitHub Desktop.
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 w
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
const length = ratings.length;
// Initialize candies array, giving each child at least one candy.
const candies = new Array(length).fill(1);
// Forward pass: ensure children with higher ratings than their left neighbor get more candies.
for (let i = 1; i < length; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// Backward pass: ensure children with higher ratings than their right neighbor get more candies.
for (let i = length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
// Take the maximum of current candies or candies required for the right neighbor.
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
// Sum up the total candies needed.
return candies.reduce((total, candyCount) => total + candyCount, 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment