Suppose we are playing a unique game and we have three values n, k, and h. We start from 0 points, then we can select a number randomly between 1 and h (inclusive) and we will get that many points. We stop when we have scored a minimum of k points. We have to find the probability that we have n or fewer points. Here any number can be chosen randomly and the outcomes all have the same probability.
So, if the input is like n = 2, k = 2, h = 10, then the output will be 0.11.
To solve this, we will follow these steps −
Define a function dp() . This will take path.
if path is same as k − 1, thens
return (minimum of n − k + 1 and h) / h
if path > n, then
if path >= k, then
return dp(path + 1) − (dp(path + h + 1) − dp(path + 1)) / h
From the main function, do the following −
if k is zero, then
if n < k , then
Let us see the following implementation to get better understanding −
class Solution: def solve(self, n, k, h): if not k: return 1 if n < k: return 0 def dp(path): if path == k− 1: return min((n− k + 1), h) / h if path > n: return 0 if path >= k: return 1 return dp(path + 1)− (dp(path + h + 1)− dp(path + 1)) / h return dp(0) ob = Solution() print(ob.solve(2,2,10))