The meaning of problems
given the difficulty of the work of a group of sequence, a given number of days. The completion of the i-th job, must first complete (0, i-1) work, difficulty of the work day is the day the work done in the most difficult that a daily difficulty of the group and for the completion of this work difficult the sum must have to work every day.
Solution to a problem
typical of dynamic programming problem, with dp [i] [j] to represent the minimum difficulty i j days to complete a total of two tasks. How recursive relationship? i j day to complete the task, as long as this j tasks assigned to it these days, the value of minimum allocation, assuming k i days to complete the task, then the first i-1 jk days necessary to complete a task, k> = i, k <= the number of tasks
such days to complete j i can be calculated minimum task difficulty of
public int minDifficulty(int[] jobDifficulty, int d) {
// 工作数量必须大于天数
if (jobDifficulty.length < d) {
return -1;
}
int[][] dp = new int[d + 1][jobDifficulty.length + 1];
dp[1][1] = jobDifficulty[0];
// 初始化第一天完成i个工作的最小难度
for (int i = 2; i <= jobDifficulty.length; i++) {
dp[1][i] = Math.max(dp[1][i - 1], jobDifficulty[i - 1]);
}
// map用来记录工作数组中i到j这个区间的最大值
int[][] map = new int[jobDifficulty.length][jobDifficulty.length];
for (int i = 0; i < jobDifficulty.length; i++) {
map[i][i] = jobDifficulty[i];
for (int j = i + 1; j < jobDifficulty.length; j++) {
map[i][j] = Math.max(jobDifficulty[j], map[i][j - 1]);
}
}
// 外层循环天数
for (int i = 2; i <= d; i++) {
// 内层循环完成的任务数,第i天要完成的任务数必须大于等于i
for (int j = i; j <= jobDifficulty.length; j++) {
dp[i][j] = Integer.MAX_VALUE;
// 总共要完成j个任务,i-1天分配部分任务,i天分配部分任务
// 计算如何分配才能使难度最小
for (int k = i - 1; k < j; k++) {
dp[i][j] = Math.min(dp[i - 1][k] + map[k][j - 1], dp[i][j]);
}
}
}
// 返回d天完成指定任务的最小难度
return dp[d][jobDifficulty.length];
}