Fair Distribution of Cookies — LeetCode 2305 Python Solution
- Problem
- #2305
- Pattern
- Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
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.