Toss Strange Coins Problem
Description
LeetCode Problem 1230.
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.
Example 1:
Input: prob = [0.4], target = 1
Output: 0.40000
Example 2:
Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0
Output: 0.03125
Constraints:
1 <= prob.length <= 10000 <= prob[i] <= 10 <= target <= prob.length- Answers will be accepted as correct if they are within
10^-5of the correct answer.
Solution
Approach: Dynamic Programming over the Coins
Toss the coins one at a time and keep f[j]: the probability of exactly j heads among the coins tossed so far. Before any toss, f[0] = 1 and the rest are 0.
When a coin with heads probability p is tossed, there are two ways to have j heads afterwards:
- there were
jheads before and this coin shows tails:f[j] * (1 - p); - there were
j - 1heads before and this coin shows heads:f[j - 1] * p.
So the new f[j] = f[j] * (1 - p) + f[j - 1] * p, and the new f[0] = f[0] * (1 - p). Only counts up to target matter, since more heads can never come back down.
To use a single array, update j from target down to 1: then f[j - 1] still holds the value from before this coin when f[j] is computed. Going upwards would use a value that already includes the current coin.
Complexity: O(n · target) time and O(target) extra space.
class Solution:
def probabilityOfHeads(self, prob: List[float], target: int) -> float:
# f[j] = probability of exactly j heads among the coins tossed so far
f = [0.0] * (target + 1)
f[0] = 1.0
for p in prob:
# Go from high j to low so f[j - 1] still holds the value before this coin.
for j in range(target, 0, -1):
f[j] = f[j] * (1 - p) + f[j - 1] * p
f[0] *= 1 - p
return f[target]