1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| public int driverMaxMoney(int[][] income) { if (income == null || income.length == 0 || (income.length & 1) != 0) { return 0; } int driverNumToA = income.length >> 1; HashMap<Integer, HashMap<Integer, Integer>> cache = new HashMap<>(); return process(income, 0, driverNumToA, cache); }
public int process(int[][] income, int index, int restForA, HashMap<Integer, HashMap<Integer, Integer>> cache) { if (cache.containsKey(index) && cache.get(index).containsKey(restForA)) { return cache.get(index).get(restForA); } if (index == income.length) { return 0; } if (restForA == 0) { return income[index][1] + process(income, index + 1, restForA, cache); } if (income.length - index == restForA) { return income[index][0] + process(income, index + 1, restForA - 1, cache); } int planA = income[index][0] + process(income, index + 1, restForA - 1, cache); int planB = income[index][1] + process(income, index + 1, restForA, cache); int ans = Math.max(planA, planB); cache.put(index, new HashMap<>(restForA, ans)); return ans; }
public int driverMaxMoneyByDP(int[][] income) { int N = income.length; int M = N >> 1; int[][] dp = new int[N+1][M+1]; for (int i = N-1; i >= 0 ; i--) { for (int j = 0; j <= M; j++) { if (j == 0) { dp[i][j] = income[i][1] + dp[i+1][j]; } else if (N - i == j) { dp[i][j] = income[i][0] + dp[i+1][j-1]; } else { int planA = income[i][0] + dp[i+1][j-1]; int planB = income[i][1] + dp[i+1][j]; dp[i][j] = Math.max(planA, planB); } } } return dp[0][M]; }
|