Maximum Candies Allocated to K Children - Binary Search [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Binary Search
Binary search for the maximum amount of candies.
How to check whether a certain amount is enough for at least k piles:
Since we can't join piles together, the amount of piles we can get from each candies[i]
is Math.floor(candies[i] / amount)
If the sum of allMath.floor(candies[i] / amount)
>= k
, the amount is enough.
n = length of candies
, m = max(candies)
Time Complexity: O(n log(m))
Space Complexity: O(1)
var maximumCandies = function(candies, k) {
let low = 0, high = Math.max(...candies);
while (low < high) {
let mid = Math.ceil((low + high) / 2);
if (isEnough(mid)) low = mid;
else high = mid - 1;
}
return low;
function isEnough(amount) {
let count = 0;
for (let i = 0; i < candies.length; i++) {
count += Math.floor(candies[i] / amount);
}
return count >= k;
}
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment