Minimum Difficulty of a Job Schedule (LeetCode 1335): Solution and Explanation
Jobs must be done in their given order over exactly d days, with at least one job per day. A day's difficulty is the hardest job done that day, and the schedule's difficulty is the sum over days. Return the minimum possible total, or -1 if there are fewer jobs than days.
Watch it run step by step
Try your own input and write the code →Intuition
Since jobs keep their order, a schedule is just a way to cut the array into d contiguous, non-empty pieces. The cost of a piece is its maximum, and we want the cheapest set of cuts. Trying every placement of d - 1 cuts among n - 1 gaps is combinatorial, but the problem has the classic structure of partition DP: the best way to finish the first i jobs in k days depends only on where day k starts and the best way to finish the earlier jobs in k - 1 days.
So define dp[i][k] as the minimum difficulty to do the first i jobs in k days. If the last day covers jobs j through i - 1, the cost is dp[j][k - 1] plus the maximum of that range. We try every valid j and keep the minimum. The base case dp[0][0] = 0 says zero jobs in zero days costs nothing, and every other state starts at infinity.
The inner loop has a nice trick for computing the range maximum. Instead of recomputing it for each j, walk j backwards from i - 1 and keep a running max_diff, updating it with jobDifficulty[j] as the last day grows one job to the left. Each candidate then costs O(1). The loop stops at j = k - 1, because the first k - 1 days need at least k - 1 jobs between them.
Approach: Partition DP with a running maximum
- Return -1 immediately if
n < d, since each day needs at least one job. - Build
dpwith n + 1 rows and d + 1 columns, filled with infinity, and setdp[0][0] = 0. - For each job count
ifrom 1 to n and each day countkfrom 1 tomin(i, d), resetmax_diff = 0. - Walk
jfromi - 1down tok - 1, treating jobsjthroughi - 1as the last day, and updatemax_diffwithjobDifficulty[j]. - Set
dp[i][k] = min(dp[i][k], dp[j][k - 1] + max_diff). - Return
dp[n][d], or -1 if it is still infinity.
Step-by-step example
jobDifficulty = [6, 5, 4, 3, 2, 1], d = 2
- With one day, the cost is the maximum of the prefix, so
dp[i][1] = 6for every i from 1 to 6. - For
dp[6][2], start withj = 5: the last day is just the job with difficulty 1, so the candidate isdp[5][1] + 1 = 7. j = 4: the last day is [2, 1] with max 2, giving 6 + 2 = 8.- Continuing down to
j = 1, the last day grows to [5, 4, 3, 2, 1] with max 5, giving 11. None beat 7. - The answer is
dp[6][2] = 7: do the first five jobs on day one (max 6) and the last job on day two (max 1).
Code: Python, Java, C++
1class Solution:
2 def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
3 n = len(jobDifficulty)
4 if n < d:
5 return -1
6
7 # dp[i][k] = min difficulty to schedule jobs[0:i] in k days
8 dp = [[float('inf')] * (d + 1) for _ in range(n + 1)]
9 dp[0][0] = 0
10
11 for i in range(1, n + 1):
12 for k in range(1, min(i, d) + 1):
13 max_diff = 0
14 # Try ending day k at position j (j < i)
15 for j in range(i - 1, k - 2, -1):
16 max_diff = max(max_diff, jobDifficulty[j])
17 dp[i][k] = min(dp[i][k], dp[j][k - 1] + max_diff)
18
19 return dp[n][d] if dp[n][d] != float('inf') else -11class Solution {
2 public int minDifficulty(int[] jobDifficulty, int d) {
3 int n = jobDifficulty.length;
4 if (n < d) return -1;
5
6 int[][] dp = new int[n + 1][d + 1];
7 for (int[] row : dp) Arrays.fill(row, Integer.MAX_VALUE);
8 dp[0][0] = 0;
9
10 for (int i = 1; i <= n; i++) {
11 for (int k = 1; k <= Math.min(i, d); k++) {
12 int maxDiff = 0;
13 for (int j = i - 1; j >= k - 1; j--) {
14 maxDiff = Math.max(maxDiff, jobDifficulty[j]);
15 if (dp[j][k - 1] != Integer.MAX_VALUE) {
16 dp[i][k] = Math.min(dp[i][k], dp[j][k - 1] + maxDiff);
17 }
18 }
19 }
20 }
21
22 return dp[n][d] == Integer.MAX_VALUE ? -1 : dp[n][d];
23 }
24}1class Solution {
2public:
3 int minDifficulty(vector<int>& jobDifficulty, int d) {
4 int n = jobDifficulty.size();
5 if (n < d) return -1;
6
7 vector<vector<int>> dp(n + 1, vector<int>(d + 1, INT_MAX));
8 dp[0][0] = 0;
9
10 for (int i = 1; i <= n; i++) {
11 for (int k = 1; k <= min(i, d); k++) {
12 int maxDiff = 0;
13 for (int j = i - 1; j >= k - 1; j--) {
14 maxDiff = max(maxDiff, jobDifficulty[j]);
15 if (dp[j][k - 1] != INT_MAX) {
16 dp[i][k] = min(dp[i][k], dp[j][k - 1] + maxDiff);
17 }
18 }
19 }
20 }
21
22 return dp[n][d] == INT_MAX ? -1 : dp[n][d];
23 }
24};Time and space complexity
O(n² × d)
There are n × d states, and each one scans up to n split points with O(1) work thanks to the running maximum.
O(n × d)
The DP table has (n + 1) × (d + 1) entries. Since each column only reads the previous one, it can be cut to O(n).
Other approaches
Top-down recursion with memoization (time O(n² × d), space O(n × d))
Define f(start, daysLeft) as the best cost for jobs from start onward, extend the current day one job at a time while tracking the max, and recurse. It is the same recurrence written from the other end and is easier for many people to derive.
Monotonic stack per day (time O(n × d), space O(n))
For each day count, process jobs left to right with a stack of decreasing difficulties so that every job knows the cheapest way to make it the maximum of the last day. It removes the inner scan and is the optimal solution, but it is considerably harder to get right.
Common mistakes
- Missing the
n < dcheck, which leavesdp[n][d]at infinity and can crash code that converts it to an integer. - Letting
jgo belowk - 1, which tries to fit k - 1 days into fewer than k - 1 jobs. - Recomputing the maximum of each range from scratch, which adds another factor of n.
- Taking the sum of the jobs on each day instead of the maximum.
Frequently asked questions
Why is this a dynamic programming problem?
The cost of the last day only depends on where it starts, and the best schedule for the earlier jobs does not depend on what happens after them. That optimal substructure lets us build answers for longer prefixes from shorter ones.
When does Minimum Difficulty of a Job Schedule return -1?
Only when there are fewer jobs than days, because every day must contain at least one job. Otherwise some valid schedule always exists.
Can the time complexity be improved beyond O(n² × d)?
Yes. A monotonic stack per day tracks, for each job, the best previous cost when that job is the maximum of the final day, which brings the total to O(n × d).