A person starts walking from position X = 0, find the probability to reach exactly on X = N if she can only take either 2 steps or 3 steps. Probability for step length 2 is given i.e. P, probability for step length 3 is 1 – P. Examples :
Input : N = 5, P = 0.20
Output : 0.32
There are two ways to reach 5.
2+3 with probability = 0.2 * 0.8 = 0.16
3+2 with probability = 0.8 * 0.2 = 0.16
So, total probability = 0.32.
In previous approach the current value dp[i] is only depend on the previous 2 values of dp i.e. dp[i-2] and dp[i-3]. So to optimize the space complexity we can store previous 4 values of Dp in 4 variables his way, the space complexity will be reduced from O(N) to O(1)
Initialize variables for dp, dp, dp, and dp as 1, 0, P, and 1-P respectively.
Iterate from i = 4 to N and use the formula dp[i] = (P)*dp[i – 2] + (1 – P) * dp[i – 3] to compute the current value of dp.
After each iteration, update the values of dp0, dp1, dp2, and dp3 to dp1, dp2, dp3, and curr respectively.
Please Login to comment...