You are given two positive integers n and limit.
Return the total number of ways to distribute n candies among 3 children such that no child gets more than limit candies.
Example 1:
Input: n = 5, limit = 2 Output: 3 Explanation: There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
Example 2:
Input: n = 3, limit = 3 Output: 10 Explanation: There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
Constraints:
1 <= n <= 1061 <= limit <= 106This approach uses three nested loops to iterate over all possible distributions of candies to check each combination of candies for three children. This method directly checks if each combination satisfies the condition and counts the valid distributions.
This C program uses three nested loops to iterate through all possible values each child can receive up to limit. It checks the remaining candies for the third child, ensuring they are also within the limit.
C++
Java
Python
C#
JavaScript
Time Complexity: O(limit^2)
Space Complexity: O(1)
Using dynamic programming, we can optimize the solution. We create a 3D DP array dp[i][j][k] where i, j, and k are the numbers of candies given to each child such that they collectively add up to n. Given constraints, we can fill the DP array by considering the subproblems of distributing fewer candies.
This C program initializes a DP table, filling valid entries based on the number of candies given to each child meeting the limit condition. The DP approach allows for efficient counting of valid distributions without recalculating repeated subproblems.
C++
Java
Python
C#
JavaScript
Time Complexity: O(limit^2)
Space Complexity: O(limit^2)
| Approach | Complexity |
|---|---|
| Brute Force Using Nested Loops | Time Complexity: O(limit^2) |
| Dynamic Programming | Time Complexity: O(limit^2) |
Candy - Leetcode 135 - Python • NeetCodeIO • 42,212 views views
Watch 9 more video solutions →Practice Distribute Candies Among Children II with our built-in code editor and test cases.
Practice on FleetCode