class Solution {
public long mostPoints(int[][] questions) {
Long[] memo = new Long[questions.length];
return dfs(questions, 0, memo);
}
private long dfs(int[][] questions, int start, Long[] memo) {
if (start >= memo.length) {
return 0;
}
if (memo[start] != null) {
return memo[start];
}
long cur = questions[start][0] + dfs(questions, start + questions[start][1] + 1, memo);
long next = dfs(questions, start+1, memo);
memo[start] = Math.max(cur, next); // just use start as key, ya it works.
return memo[start];
}
}
class Solution {
public long mostPoints(int[][] questions) {
int n = questions.length;
long[] dp = new long[200001];
for (int i = n - 1; i >= 0; i--) {
dp[i] = Math.max(
questions[i][0] + dp[i + questions[i][1] + 1],
dp[i+1]
);
}
return dp[0];
}
}
處理邊界
T: O(n)
S: O(n)
class Solution {
public long mostPoints(int[][] questions) {
int n = questions.length;
long[] dp = new long[n+1];
for (int i = n - 1; i >= 0; i--) {
int curIdx = i + questions[i][1] + 1;
long curValue = (curIdx >= n) ? 0 : dp[curIdx];
dp[i] = Math.max(questions[i][0] + curValue, dp[i+1]);
}
return dp[0];
}
}