Last active
July 12, 2023 06:09
-
-
Save mtzfox/3ad6faa38ca8a69ff49cf26c3e7069fa to your computer and use it in GitHub Desktop.
Kids with greatest number of Candies
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
var kidsWithCandies = function(candies, extraCandies) { | |
let greatestNumber = candies.map(i => i).sort((a, b) => b - a)[0]; | |
let output = []; | |
for (let i in candies) { | |
if (candies[i] + extraCandies >= greatestNumber) { | |
output.push(true); | |
} | |
else { | |
output.push(false); | |
} | |
} | |
return output; | |
}; |
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
const kidsWithCandies = (candies, extraCandies) => { | |
const max = Math.max(...candies); | |
return candies.map(candy => candy + extraCandies >= max); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From Leetcode
Given an array of kids with N candies and an extra number of N candies, return an array of boolean value results: true if current kid has the most candies and false if they don't have the most candies.
I got stuck on this at first because I forgot that the extraCandies amount was shifting as each set of values was checked.
Then I thought I'd got it and ran into another issue which made me realize that initial greatestNumber should be the highest number of the original given array, with the first test checking against that value and not 0.
Then I realized that the tests should only return true-false, but not change the largestTotal value.
This should be O(n) because it is only a single loop to check each value.