Counting heads - Dynamic Programming

Gaurav picture Gaurav · Oct 27, 2012 · Viewed 7k times · Source

Problem:

Given integers n and k, along with p1,p2,..., pn; where pi ε [0, 1], you want to determine the probability of obtaining exactly k heads when n biased coins are tossed independently at random, where pi is the probability that the ith coin comes up heads. Give an O(n2) algorithm for this task. Assume you can multiply and add two numbers in [0, 1] in O(1) time.

Can somebody help me with developing the recurrence relation so that I may code it. (The question comes from back exercise of chapter Dynamic Programming in book "Algorithms By Dasgupta")

Answer

MBo picture MBo · Oct 27, 2012

Consider the situation when (n-1) coins are tossed together and nth coin is tossed apart and take into account mutual independence.

Combine probabilities of simpler cases to get P(1..n, k) (where P(1..n, k) is the probability of obtaining exactly k heads when n coins)

Then apply this rule and fill all the cells in NxK table

Edit:

There are two possible ways to get exactly k heads with n coins -

a) if (n-1) coins have k heads, and Nth coin is tail, and

b) if (n-1) coins have k-1 heads, and Nth coin is head

so

P(n, k) = P(n-1, k) * (1 - p[n]) + P(n-1, k-1) * p[n]