2140. Solving Questions With Brainpower #1505
-
2140. Solving Questions With Brainpower Difficulty: Medium Topics: You are given a 0-indexed 2D integer array The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question
Return the maximum points you can earn for the exam. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to maximize the points we can earn from solving exam questions, given that solving a question prevents us from solving the next few questions as specified by its brainpower value. This problem can be efficiently tackled using dynamic programming. Approach
Let's implement this solution in PHP: 2140. Solving Questions With Brainpower <?php
/**
* @param Integer[][] $questions
* @return Integer
*/
function mostPoints($questions) {
$n = count($questions);
$dp = array_fill(0, $n + 1, 0);
for ($i = $n - 1; $i >= 0; $i--) {
$points = $questions[$i][0];
$bp = $questions[$i][1];
$next = $i + $bp + 1;
$solve = $points + ($next <= $n ? $dp[$next] : 0);
$skip = $dp[$i + 1];
$dp[$i] = max($solve, $skip);
}
return $dp[0];
}
// Example test cases
$questions1 = [[3,2],[4,3],[4,4],[2,5]];
echo maxPoints($questions1) . "\n"; // Output: 5
$questions2 = [[1,1],[2,2],[3,3],[4,4],[5,5]];
echo maxPoints($questions2) . "\n"; // Output: 7
?> Explanation:
This approach efficiently computes the solution in O(n) time and space complexity, making it suitable for large input sizes up to 100,000 questions. |
Beta Was this translation helpful? Give feedback.
We need to maximize the points we can earn from solving exam questions, given that solving a question prevents us from solving the next few questions as specified by its brainpower value. This problem can be efficiently tackled using dynamic programming.
Approach
dp[i]
represents the maximum points we can earn starting from thei-th
question to the end of the exam.i
, we have two choices: