Problem
You have some coins. The i
-th coin has a probability prob[i]
of facing heads when tossed.
Return the probability that the number of coins facing heads equals target
if you toss every coin exactly once.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= prob.length <= 1000
0 <= prob[i] <= 1
0 <= target ``<= prob.length
- Answers will be accepted as correct if they are within
10^-5
of the correct answer.
Solution
Method 1 – Dynamic Programming
Intuition
Let dp[i][j] be the probability of getting j heads after tossing the first i coins. For each coin, update the probability for each possible number of heads.
Approach
Use a 1D dp array (rolling array) where dp[j] is the probability of getting j heads so far. For each coin, update dp[j] from high to low.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * t)
where n = number of coins, t = target - 🧺 Space complexity:
O(t)