Beat 100% ✅ - Maximum Candies with Binary Search
CodePlease Up Vote ⬆️⬆️ If it is helpfulApproachThis approach uses binary search to efficiently determine the maximum number of candies that can be distributed
# Code
```python3 []
class Solution:
    def maximumCandies(self, candies: List[int], k: int) -> int:
        # Early check: if total candies is less than k, return 0
        total = sum(candies)
        if total < k:
            return 0
        
        # Binary search for the maximum possible allocation
        left, right = 1, total // k
        
        while left < right:
            mid = (left + right + 1) // 2  # Ceiling division to avoid infinite loop
            
            # Count how many children can get 'mid' candies
            count = sum(candy // mid for candy in candies)
            
            if count >= k:
                left = mid  # We can allocate at least 'mid' candies to each child
            else:
                right = mid - 1  # We need to allocate fewer candies
        
        return left
```

## Please Up Vote ⬆️⬆️ If it is helpful

# Approach
<!-- Describe your approach to solving the problem. -->
This approach uses **binary search** to efficiently determine the maximum number of candies that can be distributed to `k` children while ensuring each child gets the same number of candies.

### Steps:
1. **Check if distribution is possible**: If the total number of candies is less than `k`, return `0` immediately.
2. **Use binary search** to determine the maximum possible number of candies each child can receive:
   - Set `left = 1` (minimum possible allocation).
   - Set `right = total // k` (maximum possible allocation).
   - Use a **midpoint (`mid`)** to check how many children can receive at least `mid` candies.
   - If we can distribute at least `k` portions, move `left` to `mid` to search for a higher possible value.
   - Otherwise, reduce `right` to `mid - 1` to try smaller allocations.
3. **Return `left`**, which holds the maximum number of candies each child can get.

# Complexity
- **Time complexity**: $$O(n \log M)$$, where `n` is the number of candy piles and `M` is the total number of candies.  
  - Binary search runs in $$O(\log M)$$.
  - Each binary search iteration calculates `sum(candy // mid)`, which takes $$O(n)$$.
  - Thus, the total complexity is $$O(n \log M)$$.

- **Space complexity**: $$O(1)$$, as only a few extra variables are used.
['Array', 'Binary Search', 'Python3']