Skip to content

Commit 03fbb40

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent f5d4e57 commit 03fbb40

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the minimum money required to guarantee a win
4+
// for the range [1, n]. We use dynamic programming to solve the problem.
5+
int solve(int n) {
6+
// Create a 2D DP table (n+2 x n+2) initialized to 0.
7+
// dp[start][end] will store the minimum money required to guarantee a win in the range [start, end].
8+
vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));
9+
10+
// Start filling the DP table from the bottom-up approach.
11+
// We iterate from n down to 1 for the 'start' index.
12+
for (int start = n; start >= 1; start--) {
13+
// For each 'start', we iterate from 'start' to 'n' for the 'end' index.
14+
for (int end = start; end <= n; end++) {
15+
// If start == end, it means there's only one number in the range,
16+
// so no money is needed (continue to the next iteration).
17+
if (start == end) continue;
18+
else {
19+
// Initialize 'maxi' to a very large value to store the minimum money.
20+
int maxi = INT_MAX;
21+
22+
// Try every number 'i' in the range [start, end] as a possible guess.
23+
for (int i = start; i <= end; i++) {
24+
// Calculate the cost of choosing 'i':
25+
// - 'i' is the cost of guessing 'i'.
26+
// - We then look at the two subranges: [start, i-1] and [i+1, end].
27+
// The worst-case scenario is the maximum of the two subranges,
28+
// and we want to minimize the maximum cost.
29+
maxi = min(maxi, i + max(dp[start][i - 1], dp[i + 1][end]));
30+
}
31+
32+
// Store the result in the DP table for the range [start, end].
33+
dp[start][end] = maxi;
34+
}
35+
}
36+
}
37+
38+
// The result for the full range [1, n] is stored in dp[1][n].
39+
return dp[1][n];
40+
}
41+
42+
// Wrapper function to start the process with the range [1, n].
43+
int getMoneyAmount(int n) {
44+
// Call the solve function with the full range [1, n].
45+
return solve(n);
46+
}
47+
};

0 commit comments

Comments
 (0)