2226. Maximum Candies Allocated to K Children

T: O(nlogm), m is max, n is len of candies
class Solution {
    public int maximumCandies(int[] candies, long k) {
        int max = 0;
        for (int c : candies) {
            max = Math.max(c, max);
        }

        int left = 1; // distribute from 1
        int right = max;

        while (left <= right) {
            int mid = left + (right - left)/2;

            if (isOk(candies, mid, k)) {
                if (!isOk(candies, mid+1, k)) {
                    return mid;
                }
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return 0; // can't find, so ans is 0
    }

    private boolean isOk(int[] candies, int num, long k) {
        long result = 0;
        for (int c : candies) {
            result += c/num;
        }
        return result >= k;
    }
}

/*
0 to max
T: O(nlogm), m is max, n is len of candies


*/

Last updated

Was this helpful?