#2305

Fair Distribution of Cookies

Medium
ArrayDynamic ProgrammingBacktrackingBit ManipulationBitmaskBacktrackingGreedyDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(k^n)
O(k * 2^n)
Space
O(k)
O(n)
💡

Intuition

Time O(k * 2^n)Space O(n)

The optimal solution uses backtracking with pruning to minimize the search space. By keeping track of the maximum cookies for each child and stopping early when we exceed the current minimum unfairness, we can significantly reduce the number of combinations we explore.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the cookies array in descending order to prioritize larger bags.
  2. 2Step 2: Use a backtracking function to distribute cookies, tracking the current total for each child.
  3. 3Step 3: If at any point the maximum cookies for a child exceeds the current minimum unfairness, stop exploring that path.
  4. 4Step 4: Update the minimum unfairness whenever a valid distribution is found.
solution.py16 lines
1def distributeCookies(cookies, k):
2    cookies.sort(reverse=True)
3    min_unfairness = float('inf')
4    children = [0] * k
5    def backtrack(index):
6        nonlocal min_unfairness
7        if index == len(cookies):
8            min_unfairness = min(min_unfairness, max(children))
9            return
10        for i in range(k):
11            children[i] += cookies[index]
12            if max(children) < min_unfairness:
13                backtrack(index + 1)
14            children[i] -= cookies[index]
15    backtrack(0)
16    return min_unfairness

Complexity note: The time complexity is O(k * 2^n) because we explore each combination of distributing cookies, but we prune branches early when the unfairness exceeds the current minimum. The space complexity is O(n) due to the recursion stack.

  • 1Sorting the cookies helps prioritize larger bags, reducing unfairness.
  • 2Backtracking with pruning significantly reduces the number of combinations explored.

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