Talentd
FleetCode

1230. Toss Strange Coins

Medium58.1% acceptance1 companyPremium elsewhere, free here

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 <= 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.

Asked at 1 company

Hints open one at a time

Hint 1
What about solving the problem with DP?
Hint 2
Use DP with two states dp[pos][cnt], where pos represents the pos-th coin and cnt is the number of heads seen so far.
Hint 3
You can do the transitions with a little bit math.
Hint 4
For the base case, when pos == n return (cnt == target) to filter out the invalid scenarios.
3:59
Still stuck?Read 2 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[0.4]
1
Input
[0.5,0.5,0.5,0.5,0.5]
0
Your code is saved on this device.Solution