The problem is as follows:
Lazer Tag consists of a group play, where you are assigned a fixed number of bullets (popularly known as Laser shots) during the whole game. Each right shoot on your target enemy, gives you one point.
Consider the series of your hits and misses which can be represented in the form of “x” and “o” where “o” represents a hit and “x” represents a miss. Suppose the series is of the form “xxxoooxxxxooxxo”, then your final score will be equal to
3^2 + 2^2 +1^2
i.e add up the squares of every maximal number of consecutive hits in the entire game play.The probability of hitting the jth shot correctly (1≤j≤n) is P(j). In simpler terms, the probability of getting an “o” in the series at jth turn is P(j). You need to calculate the expected score at the end of your round.
I can understand a O(n^2) solution of this using memoization but the question requires a O(n) solution. I have seen the O(n) solution but I am not able to understand it. The O(n) solution is as follows:
for(i = 1; i <= n; i++)
dp[i] = (dp[i-1] + p[i-1]) * p[i];
for(i = 1; i <= n; i++)
ans+=2 * dp[i] + p[i];
where p[i] is the prob of hitting ith target. Can anyone explain how the O(n) solution works?
You can think of the scoring in the following way:
For example, a sequence of xxooox would score:
Score = 1*3+2*3 = 3+6 = 9 points. (This matches the original way of score because 9=3*3)
dp[i] computes the expected number of runs of length >1 that end at position i.
So to compute the total expected score we need to sum 2*dp[i] (as we get 2 points for every run), plus the sum of p[i] to add the expected score from getting 1 point for each hit.
The recurrence relation is because the expected number of runs of length >1 ending at position i will be:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With