Solving Questions With Brainpower

medium array dp

Problem

For each question [points, brainpower], you may solve it (gaining points but skipping the next brainpower questions) or skip to the next. Maximize total points.

Inputquestions = [[3,2],[4,3],[4,4],[2,5]]
Output5
Solve q0 (gain 3, skip 2) then q3 (gain 2) → 5.

def most_points(questions):
    n = len(questions)
    dp = [0] * (n + 1)
    for i in range(n - 1, -1, -1):
        p, b = questions[i]
        nxt = i + b + 1
        take = p + (dp[nxt] if nxt <= n else 0)
        skip = dp[i + 1]
        dp[i] = max(take, skip)
    return dp[0]
function mostPoints(questions) {
  const n = questions.length;
  const dp = new Array(n + 1).fill(0);
  for (let i = n - 1; i >= 0; i--) {
    const [p, b] = questions[i];
    const nxt = i + b + 1;
    const take = p + (nxt <= n ? dp[nxt] : 0);
    const skip = dp[i + 1];
    dp[i] = Math.max(take, skip);
  }
  return dp[0];
}
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 p = questions[i][0], b = questions[i][1];
            int nxt = i + b + 1;
            long take = p + (nxt <= n ? dp[nxt] : 0);
            long skip = dp[i + 1];
            dp[i] = Math.max(take, skip);
        }
        return dp[0];
    }
}
long long mostPoints(vector<vector<int>>& questions) {
    int n = questions.size();
    vector<long long> dp(n + 1, 0);
    for (int i = n - 1; i >= 0; i--) {
        int p = questions[i][0], b = questions[i][1];
        int nxt = i + b + 1;
        long long take = p + (nxt <= n ? dp[nxt] : 0);
        long long skip = dp[i + 1];
        dp[i] = max(take, skip);
    }
    return dp[0];
}
Time: O(n) Space: O(n)