Maximum Vacation Days

hard array dp matrix

Problem

N cities, K weeks. flights[i][j]=1 means a Monday flight from i to j. days[i][w] is the vacation days in city i on week w. Start in city 0. Max total days?

Inputflights=[[0,1,1],[1,0,1],[1,1,0]], days=[[1,3,1],[6,0,3],[3,3,3]]
Output12
DP iterating weeks backwards from K-1; O(K · N²).

def max_vacation_days(flights, days):
    N, K = len(flights), len(days[0])
    INF = float("-inf")
    dp = [INF] * N; dp[0] = 0
    for w in range(K):
        nxt = [INF] * N
        for cur in range(N):
            if dp[cur] == INF: continue
            for nxt_city in range(N):
                if nxt_city == cur or flights[cur][nxt_city] == 1:
                    nxt[nxt_city] = max(nxt[nxt_city], dp[cur] + days[nxt_city][w])
        dp = nxt
    return max(dp)
function maxVacationDays(flights, days) {
  const N = flights.length, K = days[0].length;
  const NEG = -Infinity;
  let dp = new Array(N).fill(NEG);
  dp[0] = 0;
  for (let w = 0; w < K; w++) {
    const next = new Array(N).fill(NEG);
    for (let cur = 0; cur < N; cur++) {
      if (dp[cur] === NEG) continue;
      for (let c = 0; c < N; c++) {
        if (c === cur || flights[cur][c] === 1) next[c] = Math.max(next[c], dp[cur] + days[c][w]);
      }
    }
    dp = next;
  }
  return Math.max(...dp);
}
class Solution {
    public int maxVacationDays(int[][] flights, int[][] days) {
        int N = flights.length, K = days[0].length;
        int[] dp = new int[N];
        Arrays.fill(dp, Integer.MIN_VALUE);
        dp[0] = 0;
        for (int w = 0; w < K; w++) {
            int[] next = new int[N]; Arrays.fill(next, Integer.MIN_VALUE);
            for (int cur = 0; cur < N; cur++) {
                if (dp[cur] == Integer.MIN_VALUE) continue;
                for (int c = 0; c < N; c++) {
                    if (c == cur || flights[cur][c] == 1)
                        next[c] = Math.max(next[c], dp[cur] + days[c][w]);
                }
            }
            dp = next;
        }
        int best = 0;
        for (int v : dp) best = Math.max(best, v);
        return best;
    }
}
int maxVacationDays(vector>& flights, vector>& days) {
    int N = flights.size(), K = days[0].size();
    vector dp(N, INT_MIN);
    dp[0] = 0;
    for (int w = 0; w < K; w++) {
        vector next(N, INT_MIN);
        for (int cur = 0; cur < N; cur++) {
            if (dp[cur] == INT_MIN) continue;
            for (int c = 0; c < N; c++)
                if (c == cur || flights[cur][c] == 1) next[c] = max(next[c], dp[cur] + days[c][w]);
        }
        dp = next;
    }
    return *max_element(dp.begin(), dp.end());
}
Time: O(K·N²) Space: O(N)