Problem
You are given a 0-indexed 2D integer array questions
where questions[i] = [pointsi, brainpoweri]
.
The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0
) and make a decision whether to solve or skip each question. Solving question i
will earn you pointsi
points but you will be unable to solve each of the next brainpoweri
questions. If you skip question i
, you get to make the decision on the next question.
- For example, given
questions = [[3, 2], [4, 3], [4, 4], [2, 5]]
:- If question
0
is solved, you will earn3
points but you will be unable to solve questions1
and2
. - If instead, question
0
is skipped and question1
is solved, you will earn4
points but you will be unable to solve questions2
and3
.
- If question
Return the maximum points you can earn for the exam.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= questions.length <= 10^5
questions[i].length == 2
1 <= pointsi, brainpoweri <= 10^5
Solution
Method 1 - Using Dynamic Programming
This problem can be solved using Dynamic Programming since it requires breaking the problem into overlapping subproblems optimally. We start at the first question and make two choices:
- Solve the question: Add its points to the answer and skip the next
brainpower
questions. - Skip the question: Move to the next question directly.
The goal is to find the maximum points that can be accumulated. We’ll use a bottom-up DP approach with an auxiliary array where dp[i]
represents the maximum points achievable starting from question i
.
Here is the approach:
- Define
dp[i]
wheredp[i]
represents the max points achievable starting from questioni
. - Compute
dp[i]
as the maximum of:questions[i][0]
(points for solving the question) +dp[i + questions[i][1] + 1]
(skipbrainpower
questions after solving).dp[i + 1]
(next max points if we skip the question).
- Start calculating
dp
values for each question from the last index to the first. - Return
dp[0]
as the result.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the number of questions (since we computedp[i]
for alli
). - 🧺 Space complexity:
O(n)
for thedp
array.