Skip to content

Commit 38b3d64

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent ef3bc8c commit 38b3d64

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the minimum amount of money needed to guarantee a win
4+
// in the range [start, end].
5+
int solve(int start, int end) {
6+
// Base case: If the start is greater than or equal to end, no money is needed.
7+
if (start >= end) return 0;
8+
9+
// Initialize maxi to a very large value to store the minimum amount of money.
10+
int maxi = INT_MAX;
11+
12+
// Try every number i in the range [start, end] as a possible guess.
13+
for (int i = start; i <= end; i++) {
14+
// Calculate the cost of choosing i as the guess:
15+
// - i is the cost of guessing i.
16+
// - The two ranges are [start, i-1] and [i+1, end].
17+
// Take the maximum of the two subranges since we want to ensure the worst-case scenario.
18+
maxi = min(maxi, i + max(solve(start, i - 1), solve(i + 1, end)));
19+
}
20+
21+
// Return the minimum money needed to guarantee a win for the range [start, end].
22+
return maxi;
23+
}
24+
25+
// Wrapper function to start the process with the full range [1, n].
26+
int getMoneyAmount(int n) {
27+
// Start solving from range [1, n]
28+
return solve(1, n);
29+
}
30+
};

0 commit comments

Comments
 (0)