LeetCode 1230: Toss Strange Coins Solution

Master LeetCode problem 1230 (Toss Strange Coins), a medium 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.

Problem Explanation

Explanation:

Given a list of probabilities representing the chances of getting heads when tossing a coin, we need to calculate the probability of getting a specific number of heads after tossing the coins a certain number of times.

We can solve this problem using dynamic programming. Let dp[i][j] represent the probability of getting exactly j heads after tossing the first i coins. The base case is dp[0][0] = 1 since the probability of getting 0 heads after tossing 0 coins is 1.

For each coin, we update the probabilities by considering the probability of getting heads or tails for that coin and combining it with the previous probabilities.

At the end, we return the probability of getting exactly target heads after tossing n coins, which is dp[n][target].

: :

Solution Code

class Solution {
    public double probabilityOfHeads(double[] prob, int target) {
        double[][] dp = new double[prob.length + 1][target + 1];
        dp[0][0] = 1.0;
        
        for (int i = 1; i <= prob.length; i++) {
            for (int j = 0; j <= target; j++) {
                dp[i][j] = (1 - prob[i - 1]) * (j > 0 ? dp[i - 1][j - 1] : 0)
                           + prob[i - 1] * dp[i - 1][j];
            }
        }
        
        return dp[prob.length][target];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1230 (Toss Strange Coins)?

This page provides optimized solutions for LeetCode problem 1230 (Toss Strange Coins) 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 1230 (Toss Strange Coins)?

The time complexity for LeetCode 1230 (Toss Strange Coins) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1230 on DevExCode?

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

Back to LeetCode Solutions