Problem Description
Jack has n cities available and k weeks to travel. Each city provides a fixed number of vacation days per week, given in an n x k matrix, and the cities are connected with direct flights represented by an n x n matrix. Jack starts in city 0 on Monday and can only fly (or stay) on Monday mornings. The goal is to maximize the total vacation days Jack can take over k weeks, following the travel constraints.
Key Insights
- Use dynamic programming to keep track of the maximum vacation days possible up to each week.
- Define dp[week][city] as the maximum vacation days accumulated up to that week when ending in the specified city.
- Transition from week i-1 to week i by considering all cities from which a flight (or staying) to the current city is possible (including self-transitions).
- Iterate week by week, updating the state based on available flights and the city's available vacation days.
- The final answer is the maximum value across all cities after k weeks.
Space and Time Complexity
Time Complexity: O(k * n^2), where k is the number of weeks and n is the number of cities. Space Complexity: O(n * k) if using a 2D DP array; can be optimized to O(n) using rolling arrays.
Solution
We use dynamic programming where the state dp[week][city] represents the maximum vacation days achievable up to that week if ending in the given city. For each week, iterate through each city and check all previous cities from which a valid flight (or staying in the same city) is possible. Update the dp state with the maximum vacation days so far by adding the vacation days available in the destination city for that week. Finally, the maximum value in the last week across all cities is the answer.