LeetCode 1692: Count Ways to Distribute Candies Solution

Master LeetCode problem 1692 (Count Ways to Distribute Candies), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1692. Count Ways to Distribute Candies

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We can create a 2D DP array where dp[i][j] represents the number of ways to distribute i candies to j people such that each person gets at least one candy. We can initialize the base cases where dp[0][0] = 1 and dp[0][j] = 0 for j > 0.

Then, we can iterate over the number of candies and the number of people, filling in the DP array based on the recurrence relation: dp[i][j] = dp[i][j-1] + dp[i-j][j].

Finally, the answer will be the value in dp[n][k] where n is the number of candies and k is the number of people.

Time Complexity:

The time complexity of this solution is O(n*k) where n is the number of candies and k is the number of people.

Space Complexity:

The space complexity of this solution is O(n*k) for the DP array.

:

Solution Code

class Solution {
    public int waysToDistribute(int n, int k) {
        int mod = (int)1e9 + 7;
        long[][] dp = new long[n+1][k+1];
        dp[0][0] = 1;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= k; j++) {
                dp[i][j] = (dp[i][j-1] + dp[i-1][j] * j) % mod;
            }
        }
        
        return (int)dp[n][k];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1692 (Count Ways to Distribute Candies)?

This page provides optimized solutions for LeetCode problem 1692 (Count Ways to Distribute Candies) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1692 (Count Ways to Distribute Candies)?

The time complexity for LeetCode 1692 (Count Ways to Distribute Candies) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1692 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1692 in Java, C++, or Python.

Back to LeetCode Solutions