#2226

Maximum Candies Allocated to K Children

Medium
ArrayBinary SearchBinary SearchGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log m)Space O(1)

The optimal approach uses binary search to efficiently find the maximum number of candies each child can receive. Instead of checking every possible number of candies, we narrow down the search space based on whether a certain number of candies can be allocated to k children.

⚙️

Algorithm

5 steps
  1. 1Step 1: Set low to 1 and high to the maximum pile size.
  2. 2Step 2: While low is less than or equal to high, calculate mid as the average of low and high.
  3. 3Step 3: Count how many children can be served with mid candies using a helper function.
  4. 4Step 4: If the count is at least k, update the result and move low up; otherwise, move high down.
  5. 5Step 5: Return the result.
solution.py17 lines
1# Full working Python code
2
3def canAllocate(candies, mid, k):
4    return sum(pile // mid for pile in candies) >= k
5
6
7def maxCandies(candies, k):
8    low, high = 1, max(candies)
9    result = 0
10    while low <= high:
11        mid = (low + high) // 2
12        if canAllocate(candies, mid, k):
13            result = mid
14            low = mid + 1
15        else:
16            high = mid - 1
17    return result

Complexity note: The complexity is O(n log m) where n is the number of piles and m is the maximum number of candies in a pile. The log m comes from the binary search over the possible number of candies.

  • 1Binary search helps efficiently narrow down the maximum candies each child can receive.
  • 2Understanding how to check if a certain number of candies can be allocated is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.