Skip to content

Instantly share code, notes, and snippets.

@4ver
Last active July 6, 2022 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4ver/6f59349d1894bc906c1407600c5b1693 to your computer and use it in GitHub Desktop.
Save 4ver/6f59349d1894bc906c1407600c5b1693 to your computer and use it in GitHub Desktop.
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
const isHigherValues = ratings.map((rating, index) => {
return rating > (ratings[index - 1] || 10000000) || rating > (ratings[index + 1] || 10000000)
})
const isHigherGroups = isHigherValues.reduce((prev, isHigher) => {
const topArray = prev.slice(-1)[0];
const isHigherInPrevGroup = topArray[0]
if(isHigherInPrevGroup == null) {
topArray.push(isHigher)
}
else if(isHigherInPrevGroup === isHigher) {
topArray.push(isHigher)
}
else {
const newArray = [];
newArray.push(isHigher);
prev.push(newArray);
}
return prev;
}, [[]])
const candies = isHigherGroups.flatMap((isHigherGroup) => {
const isHigher = isHigherGroup[0];
if(isHigher) {
return Array.from({length: isHigherGroup.length}, (_, i) => i + 2).reverse();
}
return isHigherGroup.map(() => 1);
})
return candies
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment