I used a binary search approach to determine the maximum number of candies each child can receive. The search range is between 1 and the maximum pile size.
The helper function canAllocate
checks if it's possible to allocate at least k
piles of size mid
.
class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
if sum(candies) < k:
return 0
left, right = 1, max(candies)
def canAllocate(mid: int) -> bool:
return sum(c // mid for c in candies) >= k
while left < right:
mid = (left + right + 1) // 2
if canAllocate(mid):
left = mid
else:
right = mid - 1
return left
- Time: O(log max(candies) * n)
- Space: O(1)
