You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].
Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.
Example 1:
Input: jobDifficulty = [6,5,4,3,2,1], d = 2
Output: 7
Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
Example 2:
Input: jobDifficulty = [9,9,9], d = 4
Output: -1
Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
Example 3:
Input: jobDifficulty = [1,1,1], d = 3
Output: 3
Explanation: The schedule is one job per day. total difficulty will be 3.
Constraints:
- 1 <= jobDifficulty.length <= 300
- 0 <= jobDifficulty[i] <= 1000
- 1 <= d <= 10
假设 dp[d][i][max]剩余天数为 d 当前 task 的 index 为 i 且当前 day 中的 task 的 difficult 的最大值为 max 时的整体 schedule 的 difficulty 的最小值。对于当前的 task, 我们有两种处理方式, 一种是放到同一天中, dp[d][i+1][max.max(curr_difficulty)]; 一种是另开一天来放置, max + dp[d-1][i+1][curr_difficulty]; 两者取最小值。
use std::collections::HashMap;
impl Solution {
fn dp(
job_difficulty: &Vec<i32>,
d: i32,
i: usize,
max: i32,
cache: &mut HashMap<(i32, usize, i32), i32>,
) -> i32 {
if i == job_difficulty.len() {
if d == 0 {
return max;
}
return -1;
}
let curr_diff = job_difficulty[i];
let append = if let Some(c) = cache.get(&(d, i + 1, max.max(curr_diff))) {
*c
} else {
Solution::dp(job_difficulty, d, i + 1, max.max(curr_diff), cache)
};
let mut new = if d > 0 {
if let Some(c) = cache.get(&(d - 1, i + 1, curr_diff)) {
*c
} else {
Solution::dp(job_difficulty, d - 1, i + 1, curr_diff, cache)
}
} else {
-1
};
if new > 0 {
new += max;
}
if append == -1 && new == -1 {
cache.insert((d, i, max), -1);
return -1;
}
if append == -1 {
cache.insert((d, i, max), new);
return new;
}
if new == -1 {
cache.insert((d, i, max), append);
return append;
}
cache.insert((d, i, max), append.min(new));
return append.min(new);
}
pub fn min_difficulty(job_difficulty: Vec<i32>, d: i32) -> i32 {
Solution::dp(&job_difficulty, d, 0, 0, &mut HashMap::new())
}
}