🧠 Greedy Candy Splitting: The Binary Search Trick Everyone Misses!
IntuitionWe want to split piles of candies into exactly k children — each getting the maximum equal amount possible.
Trying all possible values is too slow. But


### Intuition
We want to split piles of candies into exactly `k` children — each getting the **maximum equal amount possible**.  
Trying all possible values is too slow. But what if we reverse the problem and ask:  
**“Can we give each child `x` candies?”**  
This naturally leads us to **binary search**!

---

### Approach
![image.png](https://assets.leetcode.com/users/images/69739f0a-8353-44e5-bbd3-d34f8552532f_1743533697.8991878.png)

1. Use binary search over the answer: the amount of candies per child can range from `1` to `max(candies)`.
2. For each `mid`, check if it's possible to make at least `k` piles, where each pile has exactly `mid` candies.
   - Do this by summing `floor(c / mid)` for each pile.
3. If it's possible, store `mid` as a candidate and try to go higher.
4. If not, reduce the upper bound.

The result is the **maximum number of candies per child** we can guarantee across `k` kids.

---

### Complexity

**Time Complexity:**  
( O(n log m) ) where `n = len(candies)` and `m = max(candies)`

**Space Complexity:**  
( O(1) ) — only a few variables used.

---

### Code

```python []
class Solution(object):
    def maximumCandies(self, candies, k):
        l, r, ans = 1, max(candies), 0
        while l <= r:
            mid = (l + r) // 2
            if sum(c // mid for c in candies) >= k:
                ans = mid
                l = mid + 1
            else:
                r = mid - 1
        return ans
```

```javascript []
var maximumCandies = function(candies, k) {
    let left = 1, right = Math.max(...candies), ans = 0;

    const canDistribute = (mid) => {
        let count = 0;
        for (let c of candies) {
            count += Math.floor(c / mid);
        }
        return count >= k;
    };

    while (left <= right) {
        let mid = Math.floor((left + right) / 2);
        if (canDistribute(mid)) {
            ans = mid;
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return ans;
};
```

<img src="https://assets.leetcode.com/users/images/b91de711-43d7-4838-aabe-07852c019a4d_1743313174.0180438.webp" width="270"/>

['Array', 'Math', 'Binary Search', 'Heap (Priority Queue)', 'Python', 'JavaScript']