568. Maximum Vacation Days

这题就是刷房子的变种,
dp[i][j] 代表第j周最后一天在第i个城市度过的最大假期数。
dp[i][j] = max(dp[m][j - 1] + days[i][j] if there is a flight from m to i);
就比刷房子的题多了一个判断条件就是有没有航班。

class Solution {
    public int maxVacationDays(int[][] flights, int[][] days) {
        int N = flights.length;
        int K = days[0].length;
        int[][] dp = new int[N][K];
        for (int city = 0; city < N; city++) {
            dp[city][0] = -1;
            if (city == 0 || flights[0][city] == 1) {
                dp[city][0] = days[city][0];
            }
        }
        for (int w = 1; w < K; w++) {
            for (int city = 0; city < N; city++) {
                dp[city][w] = -1;
                for (int prevCity = 0; prevCity  < N; prevCity++) {
                    if (prevCity == city || flights[prevCity][city] == 1) {
                        if (dp[prevCity][w - 1] == -1) continue;
                        dp[city][w] = Math.max(dp[city][w], dp[prevCity][w - 1] + days[city][w]);
                    }
                }
            }

        }
        int ans = 0;
        for (int i = 0; i < N; i++) {
            ans = Math.max(ans, dp[i][K - 1]);
        }
        return ans;
    }
}

你可能感兴趣的:(568. Maximum Vacation Days)