Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 1, 2025 20:30
Show Gist options
  • Save tatsuyax25/fb931ff35a5bcccb21500714f9a29ed4 to your computer and use it in GitHub Desktop.
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
/**
* 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