Taro Logo

Number of Ways to Earn Points

#4 Most AskedHard
0 views
Topics:
ArraysDynamic Programming

There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [counti, marksi] indicates that there are counti questions of the ith type, and each one of them is worth marksi points.

Return the number of ways you can earn exactly target points in the exam. Since the answer may be too large, return it modulo 109 + 7.

Note that questions of the same type are indistinguishable.

  • For example, if there are 3 questions of the same type, then solving the 1st and 2nd questions is the same as solving the 1st and 3rd questions, or the 2nd and 3rd questions.

Example 1:

Input: target = 6, types = [[6,1],[3,2],[2,3]]
Output: 7
Explanation: You can earn 6 points in one of the seven ways:
- Solve 6 questions of the 0th type: 1 + 1 + 1 + 1 + 1 + 1 = 6
- Solve 4 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 1 + 2 = 6
- Solve 2 questions of the 0th type and 2 questions of the 1st type: 1 + 1 + 2 + 2 = 6
- Solve 3 questions of the 0th type and 1 question of the 2nd type: 1 + 1 + 1 + 3 = 6
- Solve 1 question of the 0th type, 1 question of the 1st type and 1 question of the 2nd type: 1 + 2 + 3 = 6
- Solve 3 questions of the 1st type: 2 + 2 + 2 = 6
- Solve 2 questions of the 2nd type: 3 + 3 = 6

Example 2:

Input: target = 5, types = [[50,1],[50,2],[50,5]]
Output: 4
Explanation: You can earn 5 points in one of the four ways:
- Solve 5 questions of the 0th type: 1 + 1 + 1 + 1 + 1 = 5
- Solve 3 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 2 = 5
- Solve 1 questions of the 0th type and 2 questions of the 1st type: 1 + 2 + 2 = 5
- Solve 1 question of the 2nd type: 5

Example 3:

Input: target = 18, types = [[6,1],[3,2],[2,3]]
Output: 1
Explanation: You can only earn 18 points by answering all questions.

Constraints:

  • 1 <= target <= 1000
  • n == types.length
  • 1 <= n <= 50
  • types[i].length == 2
  • 1 <= counti, marksi <= 50

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the exact data structure used to represent the list of question types (e.g., an array of objects, a 2D array), and what does each element contain?
  2. Can the points per question or the count of available questions be zero or negative?
  3. What should be returned if it's impossible to reach the exact target score?
  4. Are all question types distinct, or could there be multiple entries with the same point value?
  5. Could the target score be zero, and if so, is there 1 way to achieve it (by answering no questions)?

Brute Force Solution

Approach

This problem can be modeled as a bounded knapsack counting dynamic programming problem. We maintain an array representing the number of ways to achieve each total score from 0 up to the target. For each question type, we update the array by considering all valid quantities of questions that can be solved.

Here's how the algorithm would work step-by-step:

  1. Initialize a dynamic programming array of size target + 1 with all zeros except index 0 set to 1.
  2. Set up the modulo constant as 10^9 + 7 to handle large answer sizes.
  3. Iterate over each question type containing a count and mark value.
  4. Loop backwards from the target down to 0 to prevent counting transitions from the current type multiple times.
  5. For each target, iterate through solving 1 up to count questions of the current type and add the previous ways.
  6. Return the value at index target in the dynamic programming array.

Code Implementation

def ways_to_reach_target(target: int, types: list[list[int]]) -> int:
    modulo = 10**9 + 7
    # Initialize the dynamic programming table where dp[points] is the number of ways to earn points.
    dp = [0] * (target + 1)
    dp[0] = 1

    # Iterate through each question type with its count and mark value.
    for count, marks in types:
        # Iterate backwards through possible target scores to avoid using the same item multiple times.
        for current_target in range(target, -1, -1):
            # Try taking k questions of the current type.
            for solved_count in range(1, count + 1):
                points_earned = solved_count * marks
                if current_target - points_earned >= 0:
                    dp[current_target] = (dp[current_target] + dp[current_target - points_earned]) % modulo
                else:
                    break

    return dp[target]

Big(O) Analysis

Time Complexity
O(target * sum(count_i)) – For each type, we iterate through target values and up to count questions. With n types, target <= 1000, and count <= 50, the operations roughly equal n * target * count / 2, which runs well within standard time limits.
Space Complexity
O(target) – Only a single one-dimensional dynamic programming array of size target + 1 is required to store the intermediate counts.

Optimal Solution

Approach

This problem can be modeled as a bounded knapsack problem where we count the number of combinations rather than finding a maximum value. We use dynamic programming to keep track of the number of ways to form each point total up to the target score. For each question type, we update the DP table in reverse to ensure combinations are counted accurately without using items from the same type multiple times illegally.

Here's how the algorithm would work step-by-step:

  1. Initialize a dynamic programming array dp of size target + 1 with zeros, setting dp[0] to 1 as the base case.
  2. Define the modulo constant 10^9 + 7 to keep the intermediate numbers within limits.
  3. Iterate through each question type which specifies the available count and mark value.
  4. Loop backwards from target down to 1 for the current score to maintain the 0/1 bounded knapsack state.
  5. For each score, consider answering 1 to count questions of that type, accumulating valid combinations from previous scores.
  6. Update dp[target] modulo 10^9 + 7 and return dp[target] as the final result.

Code Implementation

def ways_to_reach_target(target: int, types: list[list[int]]) -> int:
    modulo = 10**9 + 7
    # Initialize dynamic programming array where dp[score] stores ways to achieve score.
    dp = [0] * (target + 1)
    dp[0] = 1
    
    for count, marks in types:
        # Iterate backwards through possible scores to prevent reusing the same question type multiple times incorrectly.
        for current_score in range(target, 0, -1):
            ways = 0
            # Sum up ways from taking from 1 to count questions of the current type.
            for question_num in range(1, count + 1):
                points = question_num * marks
                if current_score < points:
                    break
                ways = (ways + dp[current_score - points]) % modulo
            dp[current_score] = (dp[current_score] + ways) % modulo
            
    return dp[target]

Big(O) Analysis

Time Complexity
O(n * target * count) – We iterate through all n question types, and for each type, we iterate through target states. In the innermost loop, we iterate at most count times, yielding an overall time complexity bounded by O(n * target * max_count), which easily executes within the limits since n <= 50, target <= 1000, and count <= 50.
Space Complexity
O(target) – We only maintain a 1D array of size target + 1 to store the number of ways to reach each score, requiring O(target) auxiliary space.

Edge Cases

Target score is zero
How to Handle:
Return one way to achieve the target, which is by selecting no questions.
No valid combination of questions can sum up to the target score
How to Handle:
The dynamic programming table will correctly yield zero ways for the target.
Question points exceed the remaining target score
How to Handle:
Skip those branches during the state transition to prevent invalid negative targets.
Question types have a count of zero available questions
How to Handle:
Treat them as non-contributing types that do not alter the number of ways.
Large inputs leading to integer overflow in the number of ways
How to Handle:
Use 64-bit integers or apply the standard modulo arithmetic if specified by constraints.
Maximum-sized inputs with many question types and high counts
How to Handle:
Use an optimized bottom-up dynamic programming array to scale efficiently within time limits.
Multiple question types offering the exact same point value
How to Handle:
Process them sequentially in the DP state so their counts accumulate correctly without duplication.
Target score is extremely large compared to the point values
How to Handle:
Ensure the DP table is allocated up to the target size without causing out-of-bounds errors.
0/4 completed