Sponsored
Sponsored
This approach leverages dynamic programming to solve the problem. You create a DP array where each element dp[i]
represents the maximum points that can be earned starting from question i
to the last question. You decide whether to solve or skip a question based on the potential points you can earn. The solution is filled backward, starting from the last question.
Time Complexity: O(n)
Space Complexity: O(n)
1class Solution {
2 public int maxPoints(int[][] questions) {
3 int n = questions.length;
4 int[] dp = new int[n + 1];
5 for (int i = n - 1; i >= 0; --i) {
6 int solve = questions[i][0] + (i + 1 + questions[i][1] < n ? dp[i + 1 + questions[i][1]] : 0);
7 int skip = dp[i + 1];
8 dp[i] = Math.max(solve, skip);
9 }
10 return dp[0];
11 }
12}
This Java code implements the dynamic programming approach similarly to the previous solutions. It uses an array to store maximal points, iterating in reverse direction to aggregate potential solutions in each state (solving or skipping a question), and returns the best possible score from the start.
This approach uses recursion with memoization to avoid recomputing results for overlapping subproblems. It recursively decides the maximum points by considering both solving and skipping options for each question, and stores results in a memoization array for reuse. This provides an efficient way to solve the problem since it avoids redundant calculations.
Time Complexity: O(n)
Space Complexity: O(n)
1
In JavaScript, the solution implements recursion with memoization via the Map
object to store evaluations. The dfs
function recursively computes the optimal points accumulating from either the skipping or solving path for each question. The memoized checkpoint ensures optimal performance where results are efficiently stored and reused. Ultimately, the function returns the best points achievable from the first question.