3 ms/8 ms C++/JS. Binary Search. Beats 100.00%
ApproachBinary search for the appropriate number of candies. Check if the number of candies is appropriate using the test function.Complexity
Time complexity: O
# Approach
Binary search for the appropriate number of candies. Check if the number of candies is appropriate using the `test` function.

![1.png](https://assets.leetcode.com/users/images/d150e334-9ec8-41d7-a6e0-3f162401e5c8_1741951207.1881642.png)


![2.png](https://assets.leetcode.com/users/images/df997010-3309-4336-9930-38ae4cc0a175_1741951216.867072.png)


# Complexity
- Time complexity: $$O(nlogn)$$
<!-- 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 {
public:
    int maximumCandies(vector<int>& a, long long k) {
        const int n = a.size();

        const auto test = [&a, &n, &k](int x) {
            long p = 0;
            for (int i = 0; i < n; ++i) p += a[i] / x;
            return p >= k;
        };

        long s = 0;
        for (int i = 0; i < n; ++i) s += a[i];

        int i = 1;
        int j = s / k;
        if (j <= 1) return j;

        while (i <= j) {
            const int m = (i + j) / 2;
            if (test(m)) i = m + 1;
            else j = m - 1;
        }

        return j;
    }
};
```
```javascript []
const maximumCandies = (a, k) => {
    const n = a.length;
    const test = (x) => {
        let p = 0;
        for (let i = 0; i < n; ++i) p += (a[i] / x) >> 0;
        return p >= k;
    };
    let s = 0;
    for (let i = 0; i < n; ++i) s += a[i];
    let i = 1;
    let j = (s / k) >> 0;
    if (j <= 1) return j;

    while (i <= j) {
        const m = (i + j) >> 1;
        if (test(m)) i = m + 1;
        else j = m - 1;
    }
    return j;
};
```
['Array', 'Binary Search', 'C', 'C++', 'TypeScript', 'JavaScript']