Maximum Candies Allocated to K Children [C++]
IntuitionWe need to determine the maximum number of candies each child can receive when distributing candies among k children. The key observation is that binar
## **Intuition**
We need to determine the maximum number of candies each child can receive when distributing `candies` among `k` children. The key observation is that **binary search** can be applied to find the optimal maximum number of candies each child can receive.

---

## **Approach**
1. **Check Feasibility Function**:  
   - We define a helper function `canAllocate(candies, k, mid)`, which checks if we can distribute `mid` candies to each child and satisfy `k` children.
   - This is done by counting how many children can receive `mid` candies using `count += c / mid` for each `c` in `candies`.

2. **Binary Search on the Maximum Possible Candies Per Child**:
   - The search range is between `1` (minimum valid distribution) and `max(candies)` (maximum a child can receive if only one child is considered).
   - Use binary search to check if a given `mid` can be a valid maximum distribution.
   - If `canAllocate(mid) == true`, move `left` to `mid + 1` to try a larger number.
   - Otherwise, move `right` to `mid - 1` to try a smaller number.

---

## **Complexity Analysis**
- **Time Complexity**: \(O(n \log M)\)
  - **Binary search** runs in \(O(\log M)\), where \(M\) is `max(candies)`.
  - **Checking feasibility** takes \(O(n)\) for each binary search iteration.
  - Overall, this results in \(O(n \log M)\).

- **Space Complexity**: \(O(1)\)  
  - We use only a few integer variables, so space usage is constant.

---

## **Optimized C++ Solution**
```cpp
class Solution {
public:
    bool canAllocate(vector<int>& candies, long long k, int mid) {
        long long count = 0;
        for (int c : candies) {
            count += c / mid;
            if (count >= k) return true;
        }
        return false;
    }
    
    int maximumCandies(vector<int>& candies, long long k) {
        long long total_candies = accumulate(candies.begin(), candies.end(), 0LL);
        if (total_candies < k) return 0;

        int left = 1, right = *max_element(candies.begin(), candies.end()), res = 0;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (canAllocate(candies, k, mid)) {
                res = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return res;
    }
};
```
---

## **Key Takeaways**
- **Binary search** is a powerful tool when looking for an optimal maximum/minimum value.
- Using **greedy checking** inside the binary search allows us to quickly determine feasibility.
- The solution efficiently distributes the candies while minimizing unnecessary computations. 🚀
['C++']