- Related Questions & Answers
- Guess Number Higher or Lower in C++
- 8085 program to show masking of lower and higher nibbles of 8-bit number
- Ugly Number II in C++
- Confusing Number II in C++
- Strobogrammatic Number II in C++
- Number of Distinct Islands II in C++
- Convert vowels from upper to lower or lower to upper using C program
- Single Number II in Python
- Lower bound in C++
- Guess Nearest Square Root in Python
- Permutations II in C++
- Subsets II in C++
- Find the next lowest number higher than a certain number in MySQL?
- Upper or lower elements count in an array in JavaScript
- House Robber II in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we are playing the Guess Game. The rules of the game is as follows −

- Player1 pick a number from 1 to n. player2 have to guess which number is picked by player1.
- Every time player2 guess wrong, player1 will tell whether the number that is picked is higher or lower.

However, when a player guess a particular number x, and another player guess wrong, another player has to pay $x. The game will end, when player2 got the correct answer.

For example if n = 10, and the player1 has taken 8

- In the first round, player2 tells the number is 5, that is wrong, actual number is higher, then he will give $5
- In the second round, player2 tells the number is 7, that is wrong, actual number is higher, then he will give $7
- In the third round, player2 tells the number is 9, that is wrong, actual number is lower, then he will give $9

Now the game ends. So total money given is $5 + $7 + $9 = $21.

To solve this, we will follow these steps −

- create one method called cost, that is taking low, high, another table dp
- if low >= high, return 0
- if dp[low, high] is not -1, then return dp[low, high]
- ans := inf
- for i in range low to high
- ans := min of ans and (i + max of cost(low, i – 1, dp) and cost(i + 1, high, dp))

- dp[low, high] := ans and return ans
- The actual method will be like −
- make one 2d array called dp of size (n + 1) x (n + 1), and fill this with -1
- return cost(1, n, dp)

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; class Solution { public: int cost(int low, int high, vector < vector <int> >& dp){ if(low >= high)return 0; if(dp[low][high] != -1)return dp[low][high]; int ans = INT_MAX; for(int i = low; i <= high; i++){ ans = min(ans, i + max(cost(low, i - 1, dp), cost(i + 1, high, dp))); } return dp[low][high] = ans; } int getMoneyAmount(int n) { vector < vector <int> > dp(n + 1, vector <int> (n + 1, -1)); return cost(1, n, dp); } }; int main() { Solution ob1; cout << ob1.getMoneyAmount(8) << endl; return 0; }

8

12

Advertisements