AlgoMaster Logo

Fair Distribution of Cookies

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Backtracking (Brute Force)

Intuition:

The problem involves assigning cookies to children in such a way that the most "unfortunate" child (one with the most cookies) is as fortunate as possible. Given the constraints, a brute force backtracking approach can be applied to attempt all possible distributions of cookies to the children.

Approach:

  1. Utilize a backtracking approach to try distributing cookies in every possible way.
  2. Use a recursive function to decide at each step which child should receive the current cookie.
  3. After assigning all cookies, calculate the current unfairness by identifying the child with the maximum cookies and update the result.
  4. Due to the factorial time complexity of trying every distribution, this approach will be inefficient for larger inputs but demonstrates a straightforward solution.

Code:

2. Backtracking with Early Pruning

Intuition:

We can enhance the previous backtracking approach by pruning paths early when they don't promise a better result. This can be done by ensuring that no intermediate state has an unfairness greater than the currently found best solution.

Approach:

  1. Similar to the previous method, but with a check before descending deeper into recursion.
  2. Each time a cookie is assigned, check if the current unfairness already exceeds the current best solution.
  3. If it does, prune this path (do not continue recursively).
  4. This limits unnecessary computation and reduces search space.

Code: