Minimum Difficulty of a Job Schedule

Hard Dynamic Programming 2D DP

Minimum Difficulty of a Job Schedule is a hard dynamic programming problem solved with the 2d dp pattern. The best approach, optimal (bottom-up dp table), runs in O(n² · d) time and O(n · d) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every split, recursively) up.

Problem

You have a list of jobs to do in order, and jobDifficulty[i] is the difficulty of job i. To do job i, every job before it must already be done.

You must spread the jobs over exactly d days, doing at least one job each day. Each day therefore covers a contiguous block of jobs. The difficulty of a day is the largest difficulty among the jobs done that day, and the difficulty of the whole schedule is the sum of the daily difficulties.

Return the smallest possible difficulty of a schedule. If the jobs cannot be spread over d days (there are fewer jobs than days), return -1.

Examples

Example 1

Input
jobDifficulty = [7,2,6,3,1], d = 2
Output
8
Why
Job 7 comes first, so day 1 always costs at least 7. Give day 1 the jobs [7,2,6,3] (cost 7) and day 2 only [1] (cost 1): 7 + 1 = 8. Any earlier split leaves a bigger job for day 2.

Example 2

Input
jobDifficulty = [4,4], d = 3
Output
-1
Why
Every day needs at least one job, but there are only two jobs for three days.

Example 3

Input
jobDifficulty = [5,1,3,1,4], d = 3
Output
10
Why
One best split is [5] | [1] | [3,1,4], costing 5 + 1 + 4 = 10. Another is [5,1,3] | [1] | [4], also 5 + 1 + 4.

Constraints

  • 1 <= jobDifficulty.length <= 300
  • 0 <= jobDifficulty[i] <= 1000
  • 1 <= d <= 10

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every split, recursively)O(C(n - 1, d - 1) · n)O(d)
Memoized recursion (top-down DP)O(n² · d)O(n · d)
Optimal (bottom-up DP table)O(n² · d)O(n · d)

1Brute force (try every split, recursively)

TimeO(C(n - 1, d - 1) · n)Each way of choosing d - 1 cut points among the n - 1 gaps is explored, and the last day scans up to n jobs.
SpaceO(d)The recursion is d calls deep.

Let solve(i, days) be the least difficulty for jobs i..n-1 spread over exactly days days. Today takes jobs i..j for some j and costs their maximum; the rest is solve(j + 1, days - 1). Try every j that leaves at least one job for each later day. With one day left, that day takes everything that remains. Without memory this explores every way to place the d - 1 cuts.

  1. If there are fewer jobs than days, return -1.
  2. solve(i, 1) is the maximum of jobs i..n-1.
  3. Otherwise, for j from i to n - days, keep max = the largest of jobs i..j, and try max + solve(j + 1, days - 1).
  4. Return the smallest value found.
class Solution {
    public int minDifficulty(int[] jobDifficulty, int d) {
        if (jobDifficulty.length < d) return -1;
        return solve(jobDifficulty, 0, d);
    }

    // least total difficulty for jobs i..n-1 in exactly days days
    private int solve(int[] jobs, int i, int days) {
        int n = jobs.length;
        if (days == 1) {
            int max = 0;
            for (int j = i; j < n; j++) max = Math.max(max, jobs[j]);
            return max;
        }
        int best = Integer.MAX_VALUE, max = 0;
        // today does jobs i..j; leave at least one job for each later day
        for (int j = i; j <= n - days; j++) {
            max = Math.max(max, jobs[j]);
            best = Math.min(best, max + solve(jobs, j + 1, days - 1));
        }
        return best;
    }
}

2Memoized recursion (top-down DP)

TimeO(n² · d)There are n · d states, and each loops over up to n end points for today.
SpaceO(n · d)The memo table has n · (d + 1) entries; the recursion is d deep.

The brute force only ever asks about a pair (i, days): where the remaining jobs start and how many days are left. There are at most n · d such pairs, so cache each answer. A day can cost 0, so mark unknown entries with -1, not 0.

  1. If there are fewer jobs than days, return -1. Make memo[n][d + 1] filled with -1.
  2. solve(i, days): with one day left, return the maximum of jobs i..n-1.
  3. If memo[i][days] is known, return it.
  4. Otherwise loop j from i to n - days with a running maximum, take the smallest max + solve(j + 1, days - 1), store it and return it.
class Solution {
    private int[][] memo;

    public int minDifficulty(int[] jobDifficulty, int d) {
        int n = jobDifficulty.length;
        if (n < d) return -1;
        memo = new int[n][d + 1];
        for (int[] row : memo) Arrays.fill(row, -1);
        return solve(jobDifficulty, 0, d);
    }

    private int solve(int[] jobs, int i, int days) {
        int n = jobs.length;
        if (days == 1) {
            int max = 0;
            for (int j = i; j < n; j++) max = Math.max(max, jobs[j]);
            return max;
        }
        if (memo[i][days] != -1) return memo[i][days];
        int best = Integer.MAX_VALUE, max = 0;
        for (int j = i; j <= n - days; j++) {
            max = Math.max(max, jobs[j]);
            best = Math.min(best, max + solve(jobs, j + 1, days - 1));
        }
        memo[i][days] = best;
        return best;
    }
}

3Optimal (bottom-up DP table)

TimeO(n² · d)d rows of n cells, and each cell scans back over up to n split points with a running maximum.
SpaceO(n · d)The (d + 1) by (n + 1) table. Only the previous row is ever read, so two rows of size n + 1 would also do.

Build the answer one day at a time. Let dp[day][j] be the least difficulty to finish the first j jobs in exactly day days. The last of those days does some block of jobs i..j-1, so dp[day][j] is the smallest dp[day - 1][i] + max(jobs i..j-1). Walk i backwards from j - 1 so that the block maximum grows one job at a time. Each earlier day needs a job, so i never goes below day - 1. The answer is dp[d][n].

  1. If n < d, return -1. Fill dp[0..d][0..n] with infinity and set dp[0][0] = 0.
  2. For day from 1 to d, for j from day to n: set max = 0.
  3. For i from j - 1 down to day - 1: max = max(max, jobs[i]); dp[day][j] = min(dp[day][j], dp[day - 1][i] + max).
  4. Return dp[d][n].
class Solution {
    public int minDifficulty(int[] jobDifficulty, int d) {
        int n = jobDifficulty.length;
        if (n < d) return -1;
        int INF = Integer.MAX_VALUE / 2;
        // dp[day][j] = least difficulty to finish the first j jobs in exactly day days
        int[][] dp = new int[d + 1][n + 1];
        for (int[] row : dp) Arrays.fill(row, INF);
        dp[0][0] = 0;
        for (int day = 1; day <= d; day++) {
            for (int j = day; j <= n; j++) {
                int max = 0;
                // the last day does jobs i..j-1
                for (int i = j - 1; i >= day - 1; i--) {
                    max = Math.max(max, jobDifficulty[i]);
                    dp[day][j] = Math.min(dp[day][j], dp[day - 1][i] + max);
                }
            }
        }
        return dp[d][n];
    }
}

Edge cases to test

  • Fewer jobs than days: return -1
  • Exactly as many jobs as days: each day does one job, so the answer is the sum of all jobs
  • d = 1: one day does everything, so the answer is the largest job
  • Jobs with difficulty 0: a day can cost 0, so 0 cannot be used as a 'not computed yet' marker in a memo
  • The largest job always costs its full value on whichever day it lands
  • Sorted or reverse-sorted jobs, where putting the big jobs together on one day is the key

Hints

Hint 1

The days split the array into d contiguous, non-empty pieces. Each piece costs its maximum. You want the cheapest split.

Hint 2

Decide the first day: it takes jobs 0..j for some j. What is left is the same problem on the rest of the array with one day fewer.

Hint 3

As j grows, keep a running maximum for the first day instead of rescanning. Leave at least one job for each remaining day.

Hint 4

Only (start index, days left) matters, which is at most n · d states. Memoize, or fill dp[day][j] = least cost to finish the first j jobs in day days.

FAQ

What is the best time complexity for Minimum Difficulty of a Job Schedule?

Optimal (bottom-up DP table) runs in O(n² · d) time and O(n · d) extra space. d rows of n cells, and each cell scans back over up to n split points with a running maximum.

Which pattern does Minimum Difficulty of a Job Schedule use?

It is a dynamic programming problem that uses the 2d dp pattern. Other problems with the same pattern: Minimum Path Sum, Unique Paths, Unique Paths II.

Is there a brute force solution for Minimum Difficulty of a Job Schedule?

Yes. Brute force (try every split, recursively) takes O(C(n - 1, d - 1) · n) time and O(d) space. Let solve(i, days) be the least difficulty for jobs i..n-1 spread over exactly days days.

Which edge cases should I test for Minimum Difficulty of a Job Schedule?

Fewer jobs than days: return -1; Exactly as many jobs as days: each day does one job, so the answer is the sum of all jobs; d = 1: one day does everything, so the answer is the largest job; Jobs with difficulty 0: a day can cost 0, so 0 cannot be used as a 'not computed yet' marker in a memo; The largest job always costs its full value on whichever day it lands; Sorted or reverse-sorted jobs, where putting the big jobs together on one day is the key.