#2585
Number of Ways to Earn Points
HardArrayDynamic ProgrammingDynamic ProgrammingCombinatorial Counting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * target) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * target)Space O(n)
The optimal approach uses dynamic programming to build up the number of ways to achieve each possible score up to the target. This is more efficient as it avoids redundant calculations by storing previously computed results.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[i] represents the number of ways to score exactly i points.
- 2Step 2: For each type of question, update the DP array based on the number of questions and their marks.
- 3Step 3: Return dp[target] as the result.
solution.py10 lines
1def countWays(target, types):
2 MOD = 10**9 + 7
3 dp = [0] * (target + 1)
4 dp[0] = 1
5 for count, marks in types:
6 for j in range(target, -1, -1):
7 for k in range(1, count + 1):
8 if j >= k * marks:
9 dp[j] = (dp[j] + dp[j - k * marks]) % MOD
10 return dp[target]ℹ
Complexity note: The time complexity is O(n * target) because we iterate through each type and update the DP array for each possible score up to the target.
- 1Dynamic programming effectively reduces redundant calculations by storing intermediate results.
- 2Understanding how to represent the problem in terms of states (like dp arrays) is crucial for optimization.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.