Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 14, 2025 22:09
Show Gist options
  • Save Ifihan/e1cea82097d5a40845ab8d70c34361d7 to your computer and use it in GitHub Desktop.
Save Ifihan/e1cea82097d5a40845ab8d70c34361d7 to your computer and use it in GitHub Desktop.
Maximum Candies Allocated to K Children

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(log max(candies) * n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment