Problem Description
A tourist is visiting a country with n cities where every pair of different cities is directly connected. The journey lasts exactly k days (indexed from 0). At the start, the tourist can choose any city. On each day i the tourist can either: • Stay in the current city and earn stayScore[i][curr]. • Travel to another city (must be a different city) and earn travelScore[curr][dest]. Return the maximum total points the tourist can earn over the k days.
Key Insights
- Use dynamic programming where dp[i][city] represents the maximum points attainable up to day i ending in that city.
- For day 0, because any starting city is allowed, consider both the case where the tourist stays in the chosen starting city (earning stayScore[0][city]) and the case where the tourist starts in one city and immediately travels to another city (earning travelScore[start][city]).
- For subsequent days, use the previous day’s dp values to compute:
- If staying in the same city, add the corresponding stayScore for that day.
- If traveling, add the travelScore from the previous city to the destination.
- The answer will be the maximum value among all dp[k-1][city] after processing k days.
Space and Time Complexity
Time Complexity: O(k * n^2)
Space Complexity: O(n) if optimized by reusing just the previous day’s dp array, or O(k * n) if a full 2D dp table is maintained.
Solution
We solve the problem using dynamic programming.
- Define dp[i][city] as the maximum points attainable by end of day i if the tourist is in city.
- For day 0, initialize dp[0][city] as the maximum between (a) staying in that city (score = stayScore[0][city]) and (b) coming from another city by traveling (score = max{travelScore[prev][city] for all prev != city}).
- For every subsequent day i (from 1 to k-1), update dp[i][dest] by checking every possible previous city:
- If staying (prev == dest), score = dp[i-1][dest] + stayScore[i][dest].
- If traveling (prev != dest), score = dp[i-1][prev] + travelScore[prev][dest].
Then take the maximum of these over all possible previous cities.
- Finally, the answer is the maximum value in dp[k-1] across all cities.
The key trick is to correctly initialize day 0 to account for both possibilities since the starting city is freely chosen.