Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created July 19, 2020 06:07
Show Gist options
  • Save RP-3/ce6814485a9b7ee2da6a489be4493e8c to your computer and use it in GitHub Desktop.
Save RP-3/ce6814485a9b7ee2da6a489be4493e8c to your computer and use it in GitHub Desktop.
/*
Idea:
1. Find the worst-rated children and start with them
2. For Each worst child, give them just one candy (c)
3. For each neighbour,
- If they have a higher rating, give them c + 1 candies
- Otherwise give them 1 candy
4. If ever there is a conflict, round up.
The code ends up being a straightforward breadth-first search. O(n) space and time.
*/
var candy = function(ratings) {
const result = new Array(ratings.length).fill(0);
const min = Math.min(...ratings, 0);
const q = [];
ratings.forEach((r, i) => {
if(r === min) q.push([i, 1]);
});
while(q.length){
const [index, candies] = q.shift();
if(result[index] < candies) result[index] = candies;
else continue;
if(index > 0){
const left = index - 1;
const leftCandy = ratings[left] > ratings[index] ? (candies+1) : 1;
if(leftCandy > result[left]) q.push([left, leftCandy]);
}
if(index < ratings.length-1){
const right = index + 1;
const rightCandy = ratings[right] > ratings[index] ? (candies+1) : 1;
if(rightCandy > result[right]) q.push([right, rightCandy]);
}
}
return result.reduce((a, b) => a + b, 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment