Maximum Candies Allocated to K Children — LeetCode 2226 Python Solution

MediumArrayBinary Search
Problem
#2226
Reading time
2 min

The problem

You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i].

Example

Input
candies = [5,8,6], k = 3
Output
5
Explanation
We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.

Python solution

Python
class Solution:
    def maximumCandies(self, candies: List[int], k: int) -> int:
        l, r = 0, max(candies)
        while l < r:
            mid = (l + r + 1) >> 1
            if sum(x // mid for x in candies) >= k:
                l = mid
            else:
                r = mid - 1
        return l

Complexity

MeasureComplexity
TimeO(n \times \log M), where n is the length of the array \text{candies}, and M is the maximum value in the array \text{candies}
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2226. Maximum Candies Allocated to K Children is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2226. Maximum Candies Allocated to K Children?
LeetCode 2226. Maximum Candies Allocated to K Children is rated Medium on LeetCode.
What is the time complexity of LeetCode 2226. Maximum Candies Allocated to K Children?
The Python solution on this page runs in O(n \times \log M), where n is the length of the array \text{candies}, and M is the maximum value in the array \text{candies}.
What is the space complexity of LeetCode 2226. Maximum Candies Allocated to K Children?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2226. Maximum Candies Allocated to K Children cover?
LeetCode 2226. Maximum Candies Allocated to K Children is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview