We are playing the Guessing Game. The game will work as follows:
- I pick a number between
1
andn
. - You guess a number.
- If you guess the right number, you win the game.
- If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing.
- Every time you guess a wrong number
x
, you will payx
dollars. If you run out of money, you lose the game.
Given a particular n
, return the minimum amount of money you need to guarantee a win regardless of what number I pick.
class Solution:
def getMoneyAmount(self, n: int) -> int:
# Memoization
@lru_cache(None)
def sol(l, r) :
# Base cases
if r-l <= 0: return 0
if r-l == 1: return l # If only one number left, the worst case is guessing it wrong (l), as l < r
# Recursive formula
# When guessing i, the cost is i. Then, find the minimum of the worst cases for guessing l to i-1 and i+1 to r
return min((i + max(sol(l, i-1), sol(i+1, r))) for i in range(l, r+1))
return sol(1, n)