Simple and Beginner-Friendly Binary Search | Python | java | cpp || LC : 2226 || (❁´◡`❁)✨
Intuition : We need to maximize the candy piece size that can be distributed equally among k children. Using binary search, we find the largest possible size mi
# Intuition : We need to maximize the candy piece size that can be distributed equally among k children. Using binary search, we find the largest possible size mid such that the total number of pieces (sum(candies[i] / mid)) is at least k.
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach : Binary Search
<!-- Describe your approach to solving the problem. -->

# Complexity 
- Time complexity: O(n log max(candies))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```cpp []
class Solution {
    long long func(vector<int>& arr, int mid, long long k) {
        long long ans = 0;
        for (int i = 0; i < arr.size(); i++)
            if (mid > 0) ans += (arr[i] / mid);
        return ans >= k;
    }

public:
    long long maximumCandies(vector<int>& candies, long long k) {
        long long l = 1;
        long long h = *max_element(candies.begin(), candies.end());
        while (l <= h) {
            long long mid = (h + l) / 2;
            if (func(candies, mid, k)) {
                l = mid + 1;
            } else {
                h = mid - 1;
            }
        }
        return h;
    }
};
```
```python []
class Solution:
    def canDistribute(self, candies: List[int], mid: int, k: int) -> bool:
        return sum(c // mid for c in candies) >= k

    def maximumCandies(self, candies: List[int], k: int) -> int:
        l, h = 1, max(candies)
        ans = 0

        while l <= h:
            mid = (l + h) // 2
            if self.canDistribute(candies, mid, k):
                ans = mid
                l = mid + 1  # Try larger piece size
            else:
                h = mid - 1  # Reduce piece size

        return ans    
```
```Java []
class Solution {
    private boolean canDistribute(int[] candies, int mid, long k) {
        long count = 0;
        for (int c : candies) {
            count += c / mid;
        }
        return count >= k;
    }

    public int maximumCandies(int[] candies, long k) {
        int l = 1, h = Arrays.stream(candies).max().getAsInt();
        int ans = 0;

        while (l <= h) {
            int mid = l + (h - l) / 2;
            if (canDistribute(candies, mid, k)) {
                ans = mid;
                l = mid + 1;
            } else {
                h = mid - 1;
            }
        }
        return ans;
    }
}
```

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