MediumNo. 2305
Fair Distribution of Cookies — LeetCode 2305 Python Solution
- Pattern
- Backtracking
- Topics
- Bit Manipulation, Array, Dynamic Programming, Backtracking, Bitmask
- 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
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0473 | Matchsticks to Square | Medium |
| 0526 | Beautiful Arrangement | Medium |
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
| 1655 | Distribute Repeating Integers | Hard |
| 1723 | Find Minimum Time to Finish All Jobs | Hard |
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.