[Binary Search🔥] | Beginner Friendly Explanation🚀 | Java, Python, C++, JavaScript
IntuitionWe need to distribute candies among k children such that each child gets the same number of candies. Our goal is to maximize the number of candies each
# Intuition  
We need to **distribute candies** among `k` children such that each child gets the **same number of candies**. Our goal is to **maximize** the number of candies each child receives.  

Since a child can only receive **whole** candies, we can use **binary search** on the maximum possible number of candies per child.  
- If `mid` candies per child is **possible**, we try a **larger** value (`l = mid + 1`).  
- Otherwise, we reduce the value (`r = mid - 1`).  
- The highest valid `mid` is our answer.  

# Approach  
1. **Sort the candies array** to efficiently pick maximum candy values.  
2. **Use binary search** to find the largest possible `mid` (candies per child).  
   - `l = 1` (minimum possible candies per child).  
   - `r = max(candies)` (maximum possible candies per child).  
3. **Check feasibility (`isPossible` function)**:  
   - For each pile, count how many children can get `mid` candies.  
   - If `k` children can be satisfied, return `true`.  
4. **Update search range** based on feasibility and return the best result.  

# Complexity  
- **Time Complexity:** $$O(n \log m)$$, where `n` is the number of candy piles and `m` is the maximum candy count.  
- **Space Complexity:** $$O(1)$$ (only a few extra variables).  

# Code  

```java []
import java.util.Arrays;

class Solution {
    public int maximumCandies(int[] candies, long k) {
        Arrays.sort(candies); // Sort candies for efficient searching
        int length = candies.length;
        int l = 1, r = candies[length - 1]; // Binary search range
        int result = 0;

        while (l <= r) {
            int mid = l + (r - l) / 2; // Mid candies per child

            if (mid == 0) break; // Prevent division by zero
            
            if (isPossible(candies, k, mid)) {
                result = mid; // Store the valid maximum
                l = mid + 1; // Try for a larger value
            } else {
                r = mid - 1; // Reduce the value
            }
        }
        return result;
    }

    // Checks if it's possible to give 'mid' candies per child
    public boolean isPossible(int[] candies, long k, int mid) {
        for (int pile : candies) {
            k -= pile / mid; // Count how many children can get mid candies
            if (k <= 0) return true; // Enough children satisfied
        }
        return false;
    }
}
```
```python3 []
class Solution:
    def maximumCandies(self, candies: list[int], k: int) -> int:
        candies.sort() # Sort for efficiency
        l, r, result = 1, candies[-1], 0

        while l <= r:
            mid = (l + r) // 2 # Mid candies per child

            if mid == 0: break # Avoid division by zero
            
            if self.isPossible(candies, k, mid):
                result = mid # Store valid max
                l = mid + 1 # Try for more
            else:
                r = mid - 1 # Reduce value

        return result

    def isPossible(self, candies: list[int], k: int, mid: int) -> bool:
        for pile in candies:
            k -= pile // mid # Count children that can get 'mid' candies
            if k <= 0:
                return True
        return False
```
```cpp []
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    int maximumCandies(vector<int>& candies, long long k) {
        sort(candies.begin(), candies.end()); // Sort for efficiency
        int l = 1, r = candies.back(), result = 0;

        while (l <= r) {
            int mid = l + (r - l) / 2; // Mid candies per child

            if (mid == 0) break; // Prevent division by zero
            
            if (isPossible(candies, k, mid)) {
                result = mid; // Store valid max
                l = mid + 1; // Try for more
            } else {
                r = mid - 1; // Reduce value
            }
        }
        return result;
    }

private:
    bool isPossible(vector<int>& candies, long long k, int mid) {
        for (int pile : candies) {
            k -= pile / mid; // Count children that can get 'mid' candies
            if (k <= 0) return true;
        }
        return false;
    }
};
```
```javascript []
var maximumCandies = function(candies, k) {
    candies.sort((a, b) => a - b); // Sort for efficiency
    let l = 1, r = candies[candies.length - 1], result = 0;

    while (l <= r) {
        let mid = Math.floor((l + r) / 2); // Mid candies per child

        if (mid === 0) break; // Prevent division by zero
        
        if (isPossible(candies, k, mid)) {
            result = mid; // Store valid max
            l = mid + 1; // Try for more
        } else {
            r = mid - 1; // Reduce value
        }
    }
    return result;
};

// Checks if it's possible to give 'mid' candies per child
function isPossible(candies, k, mid) {
    for (let pile of candies) {
        k -= Math.floor(pile / mid); // Count children that can get 'mid' candies
        if (k <= 0) return true;
    }
    return false;
}
```

**Please Upvote⬆️** 🚀
![Screenshot 2025-02-26 230220.png](https://assets.leetcode.com/users/images/2700d36e-344c-40ba-bfb1-82090f964335_1742111864.1576836.png)

['Array', 'Binary Search', 'C++', 'Java', 'Python3', 'JavaScript']