Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 14, 2025 16:13
Show Gist options
  • Save tatsuyax25/4fdc3adb867c8ea61f735a541e746238 to your computer and use it in GitHub Desktop.
Save tatsuyax25/4fdc3adb867c8ea61f735a541e746238 to your computer and use it in GitHub Desktop.
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k.
/**
* @param {number[]} candies
* @param {number} k
* @return {number}
*/
var maximumCandies = function(candies, k) {
// Helper function to check if it's possible to distribute 'target' candies to 'k' children
function canDistribute(candies, k, target) {
let count = 0; // Count the number of children that can receive 'target' candies
for (let pile of candies) {
count += Math.floor(pile / target); // Divide the pile and count the number of children served
if (count >= k) {
return true; // If count reaches or exceeds 'k', return true
}
}
return false; // If count is less than 'k', return false
}
candies.sort((a, b) => b - a); // Sort the piles in descending order
let left = 1; // Minimum number of candies each child can get
let right = Math.max(...candies); // Maximum number of candies each child can get
while (left <= right) {
let mid = Math.floor((left + right) / 2); // Middle point to check
if (canDistribute(candies, k, mid)) {
left = mid + 1; // If it's possible to distribute 'mid' candies, increase the lower bound
} else {
right = mid - 1; // If not, decrease the upper bound
}
}
return right; // The maximum number of candies each child can get
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment