Last active
July 6, 2022 23:48
-
-
Save 4ver/6f59349d1894bc906c1407600c5b1693 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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