Leetcode-2226

Maximum Candies Allocated to K Children

Time complexity: $O(n\log M)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>

class Solution {
public:
    int maximumCandies(std::vector<int>& candies, long long k) {
        int left = 1, right = 0;
        for (int c : candies) {
            right = std::max(right, c);
        }
        
        for (int mid = (left + right) / 2; right >= left;) {
            if (check(candies, k, mid)) {
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
            mid = (left + right) / 2;
        }
        
        if (check(candies, k, left)) {
            return left;
        }
        return right;
    }
    
private:
    bool check(std::vector<int>& candies, long long k, int num) {
        for (int c : candies) {
            k -= c / num;
        }
        return k <= 0;
    }
};

Leetcode-2226