Maximum Candies Distribution Using Binary Search 🚀
IntuitionWe need to determine the maximum number of candies each child can receive, given that we have k children and an array of candies distributed in differe
# Intuition
We need to determine the maximum number of candies each child can receive, given that we have k children and an array of candies distributed in different piles. The key observation is that if x candies per child is possible, then any value less than x is also possible. This suggests a binary search approach.
# Approach
Calculate Total Candies and Maximum Candy Pile

Compute the total number of candies available.
Find the maximum number of candies in a single pile.
Edge Case

If the total number of candies is less than k, it is impossible to distribute at least one candy to each child, so return 0.
Binary Search for Maximum Candy per Child

The search space is from 1 to min(maxCandy, total/k), as no child can receive more than the largest pile, and distributing more than total/k per child is impossible.
Use binary search to find the largest possible x such that k children can be given x candies each.
Check Feasibility with Helper Function

Iterate through the candies array and check if dividing candies into groups of size mid can satisfy k children.
# Complexity
- Time complexity:
The binary search runs in O(log maxCandy).
The canAllocate function iterates through the array O(n) in the worst case.

- Space complexity:
We use only a few extra variables, so the space complexity is O(1).

# Code
```java []
class Solution {
    public int maximumCandies(int[] candies, long k) {
        long total = 0;
        int maxCandy = 0;
        
        for (int c : candies) {
            total += c;
            maxCandy = Math.max(maxCandy, c);
        }
        
        if (total < k) return 0;
        
        int left = 1, right = (int) Math.min(maxCandy, total / k), result = 0;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (canAllocate(candies, k, mid)) {
                result = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }

    private boolean canAllocate(int[] candies, long k, int mid) {
        long count = 0;
        for (int c : candies) {
            count += c / mid;
            if (count >= k) return true;
        }
        return false;
    }
}

```
['Java']