![]() |
VOOZH | about |
Given N Chocolates, distribute them among K Persons. We are also given an array of maxChocolates[] of size K. The Chocolates can be distributed in such a manner that the ith person has the capacity maxChocolates[i] (both inclusive). Find the total number of ways to distribute the chocolates such that no chocolates are left, and no person gets more chocolate than his capacity.
Examples:
Input: N = 3, K = 2, maxChocolates = [2, 3]
Output: 3
Explanation: There are 3 ways to distribute the chocolates:
- Person1 gets 0 chocolate and Person2 gets 3 chocolates.
- Person1 gets 1 chocolate and Person2 gets 2 chocolates.
- Person1 gets 2 chocolates and Person2 gets 1 chocolate.
Input: N = 4, K = 2, maxChocolates = [1, 1]
Output: 0
Explanation: There is no way to distribute the 4 chocolates among these 2 persons.
Approach: The problem can be solved using the following appraoch:
The problem can be solved using Dynamic Programming. We can maintain a 2D array dp[][] such that dp[i][j] will store the number of ways to distribute i chocolates among j persons. Now, we iterate over all the persons, and for every person i, we explore all the possibilities of distributing the chocolates to the ith person.
dp[i][j] = number of ways to distribute i chocolates till the person at index j
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above appraoch:
3
Time Complexity: O(N * K * K), where N is the number of chocolates and K is the number of persons.
Auxiliary Space: O(N * K)
This iterative approach avoids recursion and calculates the result in a bottom-up manner using dynamic programming.
3
Time Complexity: O(N * K * maxChocolates_max), where maxChocolates_max is the maximum value in the maxChocolates array.
Auxiliary Space:O(N * K)