Problem Description
You are given an array of coin probabilities where the i-th coin lands heads with probability prob[i]. Toss all coins exactly once and return the probability that exactly target coins show heads.
Key Insights
- Each coin toss is an independent event.
- Use dynamic programming (DP) to calculate the probability of obtaining a specific number of heads.
- For each coin, update the DP array in reverse order to avoid overwriting earlier computed probabilities.
- The recurrence relation is: dp[j] = dp[j-1] * prob[i] + dp[j] * (1 - prob[i]).
Space and Time Complexity
Time Complexity: O(n * target), where n is the number of coins.
Space Complexity: O(target), using a one-dimensional DP array.
Solution
We employ a dynamic programming approach where dp[j] represents the probability of getting exactly j heads at the current stage. We initialize dp[0] to 1 (base case: zero coins tossed yields 0 heads with probability 1), and then for each coin, update the dp array by iterating from target down to 0. This avoids interference from the current coin’s updates affecting future calculations within the same iteration. The final answer is dp[target] after processing all coins.