Number of Ways to Earn Points — LeetCode 2585 Python Solution

HardArrayDynamic Programming
Problem
#2585
Reading time
3 min

The problem

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.

Example

Input
target = 6, types = [[6,1],[3,2],[2,3]]
Output
7
Explanation
You can earn 6 points in one of the seven ways:

Python solution

Python
class Solution:
    def waysToReachTarget(self, target: int, types: List[List[int]]) -> int:
        n = len(types)
        mod = 10**9 + 7
        f = [[0] * (target + 1) for _ in range(n + 1)]
        f[0][0] = 1
        for i in range(1, n + 1):
            count, marks = types[i - 1]
            for j in range(target + 1):
                for k in range(count + 1):
                    if j >= k * marks:
                        f[i][j] = (f[i][j] + f[i - 1][j - k * marks]) % mod
        return f[n][target]

Complexity

MeasureComplexity
TimeO(n \times target \times count)
SpaceO(n \times target) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2585. Number of Ways to Earn Points is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2585. Number of Ways to Earn Points?
LeetCode 2585. Number of Ways to Earn Points is rated Hard on LeetCode.
What is the time complexity of LeetCode 2585. Number of Ways to Earn Points?
The Python solution on this page runs in O(n \times target \times count).
What is the space complexity of LeetCode 2585. Number of Ways to Earn Points?
The Python solution on this page uses O(n \times target) auxiliary space.
What topics does LeetCode 2585. Number of Ways to Earn Points cover?
LeetCode 2585. Number of Ways to Earn Points is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview