Skip to content

2226. Maximum Candies Allocated to K Children 👍

  • Time: $O(n\log(\Sigma |\texttt{candies[i]}|))$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int maximumCandies(vector<int>& candies, long long k) {
    int l = 1;
    int r = accumulate(candies.begin(), candies.end(), 0L) / k;

    while (l < r) {
      const int m = (l + r) / 2;
      if (numChildren(candies, m) < k)
        r = m;
      else
        l = m + 1;
    }

    return numChildren(candies, l) >= k ? l : l - 1;
  }

 private:
  long numChildren(const vector<int>& candies, int m) {
    return accumulate(candies.begin(), candies.end(), 0L,
                      [&](long subtotal, int c) { return subtotal + c / m; });
  };
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int maximumCandies(int[] candies, long k) {
    int l = 1;
    int r = (int) (Arrays.stream(candies).asLongStream().sum() / k);

    while (l < r) {
      final int m = (l + r) / 2;
      if (numChildren(candies, m) < k)
        r = m;
      else
        l = m + 1;
    }

    return numChildren(candies, l) >= k ? l : l - 1;
  }

  private long numChildren(int[] candies, int m) {
    return Arrays.stream(candies).asLongStream().reduce(0L, (subtotal, c) -> subtotal + c / m);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maximumCandies(self, candies: list[int], k: int) -> int:
    l = 1
    r = sum(candies) // k

    def numChildren(m: int) -> bool:
      return sum(c // m for c in candies)

    while l < r:
      m = (l + r) // 2
      if numChildren(m) < k:
        r = m
      else:
        l = m + 1

    return l if numChildren(l) >= k else l - 1