Skip to content

Commit da4e088

Browse files
authored
Create 2140. Solving Questions With Brainpower1 (#758)
2 parents 9282ce9 + c822dee commit da4e088

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the maximum points
4+
long long solve(long long idx, int n, vector<vector<int>>& questions, vector<long long>& dp) {
5+
// Base Case: If index exceeds or reaches the last question, return 0 (No more questions left)
6+
if (idx >= n) {
7+
return 0;
8+
}
9+
10+
// If the answer for this index is already calculated, return it (Memoization step)
11+
if (dp[idx] != -1) {
12+
return dp[idx];
13+
}
14+
15+
// **Choice 1: Take the current question**
16+
// - We add the points of the current question
17+
// - Move to the next question index: `idx + questions[idx][1] + 1` (Skipping cooldown questions)
18+
long long take = solve(idx + questions[idx][1] + 1, n, questions, dp) + questions[idx][0];
19+
20+
// **Choice 2: Skip the current question**
21+
// - Simply move to the next question (`idx + 1`)
22+
long long not_take = solve(idx + 1, n, questions, dp);
23+
24+
// Store the maximum result in dp array and return it
25+
return dp[idx] = max(take, not_take);
26+
}
27+
28+
// Main function to initialize and call recursion
29+
long long mostPoints(vector<vector<int>>& questions) {
30+
int n = questions.size(); // Get total number of questions
31+
vector<long long> dp(n + 1, -1); // DP array initialized with -1 (to indicate uncomputed states)
32+
33+
return solve(0, n, questions, dp); // Start solving from the first question
34+
}
35+
};

0 commit comments

Comments
 (0)