Created
April 1, 2025 20:30
-
-
Save tatsuyax25/fb931ff35a5bcccb21500714f9a29ed4 to your computer and use it in GitHub Desktop.
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 whe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Function to calculate the maximum points that can be earned | |
* by answering questions strategically. | |
* @param {number[][]} questions - Array of questions, where each question is represented as [points, brainpower]. | |
* @return {number} - The maximum points that can be achieved. | |
*/ | |
var mostPoints = function(questions) { | |
const n = questions.length; | |
// Memoization array to store results of subproblems | |
const memo = new Array(n).fill(-1); | |
/** | |
* Recursive function to calculate the maximum points starting from question i. | |
* @param {number} i - Current question index. | |
* @return {number} - Maximum points from question i onwards. | |
*/ | |
function dp(i) { | |
// Base case: If index is out of bounds, return 0 | |
if (i >= n) return 0; | |
// Return the result if already computed | |
if (memo[i] !== -1) return memo[i]; | |
// Option 1: Take the current question and skip the ones blocked by brainpower | |
const take = questions[i][0] + dp(i + questions[i][1] + 1); | |
// Option 2: Skip the current question | |
const notTake = dp(i + 1); | |
// Store the maximum result in memo and return it | |
memo[i] = Math.max(take, notTake); | |
return memo[i]; | |
} | |
// Start the recursion from the first question | |
return dp(0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment