MediumNo. 2305

Fair Distribution of Cookies — LeetCode 2305 Python Solution

Topics
Bit Manipulation, Array, Dynamic Programming, Backtracking, Bitmask
Reading time
4 min

The problem

You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to.

Example

Input
cookies = [8,15,10,20,8], k = 2
Output
31
Explanation
One optimal distribution is [8,15,8] and [10,20]

Python solution

PythonSolution
class Solution:
    def distributeCookies(self, cookies: List[int], k: int) -> int:
        def dfs(i):
            if i >= len(cookies):
                nonlocal ans
                ans = max(cnt)
                return
            for j in range(k):
                if cnt[j] + cookies[i] >= ans or (j and cnt[j] == cnt[j - 1]):
                    continue
                cnt[j] += cookies[i]
                dfs(i + 1)
                cnt[j] -= cookies[i]

        ans = inf
        cnt = [0] * k
        cookies.sort(reverse=True)
        dfs(0)
        return ans

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 2305. Fair Distribution of Cookies is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2305. Fair Distribution of Cookies?

LeetCode 2305. Fair Distribution of Cookies is rated Medium on LeetCode.

What topics does LeetCode 2305. Fair Distribution of Cookies cover?

LeetCode 2305. Fair Distribution of Cookies is tagged Bit Manipulation, Array, Dynamic Programming, Backtracking and Bitmask 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.

Free to download. Check it runs on your machine, then pick a plan.