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
| class Solution { int[] jobDifficulty; int[][] cache;
public int minDifficulty(int[] jobDifficulty, int d) { int n = jobDifficulty.length; if (n < d) return -1; this.jobDifficulty = jobDifficulty; this.cache = new int[d][n]; for (int i = 0; i < d; ++i) { Arrays.fill(cache[i], -1); } return dfs(d - 1, n - 1); }
private int dfs(int i, int j) { if (cache[i][j] != -1) return cache[i][j]; if (i == 0) { int max = 0; for (int k = 0; k <= j; ++k) { max = Math.max(max, jobDifficulty[k]); } return cache[i][j] = max; } int max = 0, ans = Integer.MAX_VALUE; for (int k = j; k >= i; --k) { max = Math.max(max, jobDifficulty[k]); ans = Math.min(ans, dfs(i - 1, k - 1) + max); } return cache[i][j] = ans; } }
|