Maximum Points Tourist Can Earn Problem
Description
LeetCode Problem 3332.
You are given two integers, n and k, along with two 2D integer arrays, stayScore and travelScore.
A tourist is visiting a country with n cities, where each city is directly connected to every other city. The tourist's journey consists of exactly k 0-indexed days, and they can choose any city as their starting point.
Each day, the tourist has two choices:
- Stay in the current city: If the tourist stays in their current city
currduring dayi, they will earnstayScore[i][curr]points. - Move to another city: If the tourist moves from their current city
currto citydest, they will earntravelScore[curr][dest]points.
Return the maximum possible points the tourist can earn.
Example 1:
Input: n = 2, k = 1, stayScore = [[2,3]], travelScore = [[0,2],[1,0]]
Output: 3
Explanation:
The tourist earns the maximum number of points by starting in city 1 and staying in that city.
Example 2:
Input: n = 3, k = 2, stayScore = [[3,4,2],[2,1,2]], travelScore = [[0,2,1],[2,0,4],[3,2,0]]
Output: 8
Explanation:
The tourist earns the maximum number of points by starting in city 1, staying in that city on day 0, and traveling to city 2 on day 1.
Constraints:
1 <= n <= 2001 <= k <= 200n == travelScore.length == travelScore[i].length == stayScore[i].lengthk == stayScore.length1 <= stayScore[i][j] <= 1000 <= travelScore[i][j] <= 100travelScore[i][i] == 0
Solution
Approach: Dynamic programming over days
Let f[i][j] be the most points the tourist can have after i days if they are in city j. Before the first day they may start anywhere, so f[0][j] = 0.
On day i (1-indexed), the tourist moves from city h to city j. If h == j they stay and earn stayScore[i - 1][j]; otherwise they travel and earn travelScore[h][j]. So f[i][j] is the maximum over all h of f[i - 1][h] plus that score. The answer is the maximum of f[k].
Complexity: O(k * n^2) time and O(k * n) space.
from math import inf
class Solution:
def maxScore(
self, n: int, k: int, stayScore: List[List[int]], travelScore: List[List[int]]
) -> int:
f = [[-inf] * n for _ in range(k + 1)]
f[0] = [0] * n
for i in range(1, k + 1):
for j in range(n):
for h in range(n):
f[i][j] = max(
f[i][j],
f[i - 1][h]
+ (stayScore[i - 1][j] if j == h else travelScore[h][j]),
)
return max(f[k])