We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Solving Questions With Brainpower

Number: 2262

Difficulty: Medium

Paid? No

Companies: Google, Meta, Amazon


Problem Description

Given a list of questions where each question has two properties: points and brainpower, you must process the questions sequentially. When you choose to solve a question, you earn its points but then must skip the next brainpower number of questions. Alternatively, you can skip a question to consider the next one. The goal is to maximize the total points earned.


Key Insights

  • Use dynamic programming to decide for each question whether to solve or skip.
  • The decision at each question depends on future questions, making it ideal for a backward DP approach.
  • Maintain a DP array where dp[i] represents the maximum points from question i to the end.
  • For each question, compare the result of solving the current question (points plus dp at the index after the brainpower skip) with skipping it (dp[i+1]).

Space and Time Complexity

Time Complexity: O(n) where n is the number of questions.
Space Complexity: O(n) for the DP array.


Solution

We use a dynamic programming approach that processes the questions in reverse order. For each question at index i:

  1. Calculate the index you would reach if you decide to solve the question: jumpIndex = i + brainpower[i] + 1.
  2. The option to solve the question earns you points[i] plus the maximum points from jumpIndex (or 0 if jumpIndex is out of bounds).
  3. The option to skip the question simply gives you dp[i+1].
  4. Set dp[i] as the maximum between these two options. The final answer is stored in dp[0].

Code Solutions

# Function to calculate the maximum points
def mostPoints(questions):
    n = len(questions)
    # Initialize DP array with n+1 elements, all 0.
    dp = [0] * (n + 1)
    
    # Process questions in reverse order.
    for i in range(n - 1, -1, -1):
        points, brainpower = questions[i]
        # Calculate the index after skipping brainpower number of questions.
        jump_index = i + brainpower + 1
        
        # If jump_index is within bounds, add its DP value; otherwise, add 0.
        solve_option = points + (dp[jump_index] if jump_index < n else 0)
        skip_option = dp[i + 1]  # Option to skip the current question.
        
        # Choose the maximum points between solving and skipping.
        dp[i] = max(solve_option, skip_option)
    
    return dp[0]

# Example usage:
# questions = [[3,2],[4,3],[4,4],[2,5]]
# print(mostPoints(questions))  # Output: 5
← Back to All Questions