✅✅ Binary Search || Beginner Friendly || Easy Solution
Intuition
We need to distribute candies among k children such that each child gets the same maximum number of candies.
The goal is to maximize this number.
Inst
# **Intuition**
- We need to distribute `candies` among `k` children such that **each child gets the same maximum number of candies**.
- The goal is to **maximize** this number.
- Instead of distributing candies one by one, we **binary search** for the maximum number of candies each child can receive.


# **Approach**
### **1. Binary Search on Possible Candy Distribution**
- The possible range of answers is `[1, max(candies)]` (1 means each child gets at least one, `max(candies)` means one child gets all candies).
- We perform **binary search** to determine the maximum candies (`mid`) each child can get.

### **2. Checking Feasibility (`canDistr` function)**
- Given a `mid` value (candies per child), check if we can distribute them among `k` children:
  - Count how many children we can satisfy by doing `candies[i] / mid`.
  - If the count ≥ `k`, it's possible.
  - If `k` children can get `mid` candies each, move **right** to check for a larger `mid`.
  - Otherwise, move **left** to decrease `mid`.

### **3. Binary Search Execution**
- **If `mid` candies per child is possible** → move **right** (`l = mid + 1`).
- **Otherwise** → move **left** (`r = mid - 1`).
- The final answer is stored in `ans`.

# **Time Complexity Analysis**
1. **Binary Search:**  
   - The search space is `[1, max(candies)]`, which takes **O(log maxC)**.

2. **Checking Feasibility (`canDistr`)**  
   - **O(N)** for iterating over `candies`.

3. **Total Complexity:**  
   - **O(N log maxC)**.

# **Space Complexity**
- **O(1)** (only variables used).


# Code
```cpp []
class Solution {
public:
    int N;
    bool canDistr(vector<int>&candies,long long k,int mid){
        for(int i=0;i<N;i++){
            k-=candies[i]/mid;

            // Early return - All children got mid candies
            if(k<=0) return true;
        }
        // All children got the mid candies
        return k<=0;
    }
    int maximumCandies(vector<int>& candies, long long k) {
        N=candies.size();
        int maxC=0;
        long long total=0;
        for(int i=0;i<N;i++){
            total+=candies[i];
            maxC=max(maxC,candies[i]);
        }
        if(total<k) return 0;
        int l=1;
        int r=maxC;
        int ans=0;
        while(l<=r){
            int mid=l+(r-l)/2;
            if(canDistr(candies,k,mid)){
                ans=mid;
                l=mid+1;
            } else{
                r=mid-1;
            }
        }
        return ans;
    }
};
```
# Have a Good Day 😊 UpVote?
['Array', 'Binary Search', 'C++']