Skip to content

Instantly share code, notes, and snippets.

@YanivHaramati
Last active August 29, 2015 14:06
Show Gist options
  • Save YanivHaramati/7e9c7243247d019c1a88 to your computer and use it in GitHub Desktop.
Save YanivHaramati/7e9c7243247d019c1a88 to your computer and use it in GitHub Desktop.
Candy Problem from leetcode
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?
var box = new CandyBox([2,4,7,8,3,4,6,2]);
var count = box.candyCount(); // => [1,2,3,4,1,2,3,1] => 17
var CandyBox = function(ratings) {
var self = {};
self.init = function(ratings) {
self.ratings = ratings;
}
self.countCandies = function() {
if (self.ratings.length <= 1) return ratings.length;
ratings = self.ratings;
var candies = ratings.map(function () { return 0; });
var minPoints = [];
// left edge
if (ratings[1] >= ratings[0]) {
candies[0] = 1;
minPoints.push(0);
}
// right edge
var end = ratings.length - 1;
if (end > 0 && ratings[end] <= ratings[end - 1]) {
candies[end] = 1;
minPoints.push(end);
}
// find other min-points
if (end - 1 > 0) {
for (var i = 1; i < end - 1; i++) {
if (candies[i] != 1) {
// if left AND right are greater than current rating, set min val.
var currentRating = ratings[i];
if (ratings[i - 1] >= currentRating && ratings[i + 1] >= currentRating) {
candies[i] = 1;
minPoints.push(i);
}
}
}
}
// increment run
var inc = function (i, val) {
// increment current
var curVal = (val) ? val + 1 : candies[i];
candies[i] = curVal;
// left
if (i - 1 >= 0 && candies[i - 1] == 0) {
inc(i - 1, curVal);
}
// right
if (i + 1 <= end && candies[i + 1] == 0) {
inc(i + 1, curVal);
}
};
minPoints.forEach(function(min) {
inc(min);
});
return candies.reduce(function (prev, cur) {
return prev + cur;
});
};
self.init(ratings);
return self;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment