#3332
Maximum Points Tourist Can Earn
MediumArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n^k) | O(n^2 * k) |
| Space | O(k) | O(n * k) |
💡
Intuition
Time O(n^2 * k)Space O(n * k)
The optimal solution uses dynamic programming to build up the maximum points achievable day by day, considering both staying and traveling options. This significantly reduces the number of calculations by storing intermediate results.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP table where dp[day][city] represents the maximum points achievable on 'day' while in 'city'.
- 2Step 2: For each day, calculate the maximum points for each city by considering both staying and moving to other cities.
- 3Step 3: Return the maximum value from the last day across all cities.
solution.py8 lines
1def maxPoints(n, k, stayScore, travelScore):
2 dp = [[0] * n for _ in range(k)]
3 for city in range(n):
4 dp[0][city] = stayScore[0][city]
5 for day in range(1, k):
6 for city in range(n):
7 dp[day][city] = stayScore[day][city] + max(dp[day - 1][c] + travelScore[c][city] for c in range(n))
8 return max(dp[k - 1])ℹ
Complexity note: This complexity arises because we fill a DP table of size k x n, where each cell requires checking all previous cities.
- 1Dynamic programming helps optimize the exploration of paths by storing intermediate results.
- 2Understanding the structure of the problem allows for breaking it down into manageable subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.