#1335

Minimum Difficulty of a Job Schedule

Hard
ArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n² * d)
Space
O(1)
O(n * d)
💡

Intuition

Time O(n² * d)Space O(n * d)

Using dynamic programming, we can break down the problem into smaller subproblems. We maintain a DP table where each entry represents the minimum difficulty of scheduling jobs up to a certain index with a given number of days left.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[i][j] represents the minimum difficulty of scheduling the first i jobs in j days.
  2. 2Step 2: Iterate through the number of days and for each day, calculate the maximum job difficulty for the jobs scheduled on that day.
  3. 3Step 3: Update the DP table based on the previous day's minimum difficulty and the maximum job difficulty for the current day.
solution.py16 lines
1# Full working Python code
2import sys
3
4def minDifficulty(jobDifficulty, d):
5    n = len(jobDifficulty)
6    if n < d:
7        return -1
8    dp = [[sys.maxsize] * (d + 1) for _ in range(n + 1)]
9    dp[0][0] = 0
10    for j in range(1, d + 1):
11        for i in range(j, n + 1):
12            max_difficulty = 0
13            for k in range(i, j - 1, -1):
14                max_difficulty = max(max_difficulty, jobDifficulty[k - 1])
15                dp[i][j] = min(dp[i][j], dp[k - 1][j - 1] + max_difficulty)
16    return dp[n][d]

Complexity note: The time complexity is O(n² * d) because for each day, we may need to check all jobs up to that day, and we do this for each day, leading to a quadratic relationship with respect to the number of jobs.

  • 1Understanding how to partition the jobs effectively is crucial for minimizing difficulty.
  • 2Dynamic programming allows us to build solutions incrementally, making it easier to manage complex dependencies.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.