Skip to content

Instantly share code, notes, and snippets.

@mtzfox
Last active July 12, 2023 06:09
Show Gist options
  • Save mtzfox/3ad6faa38ca8a69ff49cf26c3e7069fa to your computer and use it in GitHub Desktop.
Save mtzfox/3ad6faa38ca8a69ff49cf26c3e7069fa to your computer and use it in GitHub Desktop.
Kids with greatest number of Candies
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;
};
const kidsWithCandies = (candies, extraCandies) => {
const max = Math.max(...candies);
return candies.map(candy => candy + extraCandies >= max);
};
@mtzfox
Copy link
Author

mtzfox commented Jul 12, 2023

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.

  • greatestNumber starts with largest array number - sort descending and return first value.
  • for...in loop will check if each Current value (individual amount + extra) is greatest, if yes push true to output, if false push false.
  • if false return false.

This should be O(n) because it is only a single loop to check each value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment