Minimum Difficulty of a Job Schedule Problem
Description
LeetCode Problem 1335.
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i^th 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 i^th 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 <= 3000 <= jobDifficulty[i] <= 10001 <= d <= 10
Solution
Approach: Dynamic Programming
The jobs are done in order, so a schedule just cuts the list of jobs into d non-empty consecutive pieces, one per day, and costs the sum of each piece's maximum. If there are fewer jobs than days, some day would be empty, so the answer is -1.
Let f[i] be the least difficulty of doing the first i jobs in the days planned so far. With zero days, only f[0] = 0 is possible. To add one more day, we try every choice for its jobs: if the new day does jobs k - 1 through i - 1 (0-indexed), the earlier days did the first k - 1 jobs, so
g[i] = min over k of (f[k - 1] + max(jobDifficulty[k - 1..i - 1]))
By trying k from i downwards, the maximum of the day's jobs can be updated one job at a time instead of being recomputed. After day days at least day jobs are done, so i starts at day and k stops at day, which keeps every earlier day non-empty. After d rounds, f[n] is the answer.
Complexity: O(n2·d) time and O(n) extra space, keeping only the rows for the previous day and the current one.
class Solution:
def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
n = len(jobDifficulty)
if n < d:
return -1 # every day needs at least one job
INF = 10**9
# f[i]: the least difficulty to finish the first i jobs in the days planned so far
f = [0] + [INF] * n
for day in range(1, d + 1):
g = [INF] * (n + 1)
for i in range(day, n + 1): # `day` days take at least `day` jobs
hardest = 0
# Today does jobs k-1 .. i-1; the earlier days did the first k-1 jobs.
for k in range(i, day - 1, -1):
hardest = max(hardest, jobDifficulty[k - 1])
g[i] = min(g[i], f[k - 1] + hardest)
f = g
return f[n]