Minimum Time to Complete All Tasks - Problem

There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks where tasks[i] = [starti, endi, durationi] indicates that the ith task should run for a total of durationi seconds (not necessarily continuous) within the inclusive time range [starti, endi].

You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.

Return the minimum time during which the computer should be turned on to complete all tasks.

Input & Output

Example 1 — Basic Case
$ Input: tasks = [[2,3,1],[2,5,3]]
Output: 4
💡 Note: Task 1 needs 1 second in [2,3], task 2 needs 3 seconds in [2,5]. Optimal: run at times 2,3,4,5 for total 4 seconds.
Example 2 — Single Task
$ Input: tasks = [[1,3,2]]
Output: 2
💡 Note: One task needs 2 seconds within [1,3]. We can run at any 2 time points, minimum runtime is 2.
Example 3 — Non-overlapping
$ Input: tasks = [[1,2,1],[3,4,1]]
Output: 2
💡 Note: Tasks don't overlap in time windows. Need 1 second for each task, total runtime is 2.

Constraints

  • 1 ≤ tasks.length ≤ 2000
  • tasks[i].length == 3
  • 1 ≤ starti ≤ endi ≤ 2000
  • 1 ≤ durationi ≤ tasks[i][1] - tasks[i][0] + 1

Visualization

Tap to expand
Minimum Time to Complete All Tasks INPUT tasks = [[2,3,1],[2,5,3]] Task 0: [2, 3, 1] Start:2, End:3, Duration:1 Task 1: [2, 5, 3] Start:2, End:5, Duration:3 Timeline View 1 2 3 4 5 6 T0 T1 Time ranges for each task ALGORITHM STEPS 1 Sort by End Time T0[end=3], T1[end=5] 2 Process Task 0 Need 1s in [2,3] Pick time=3 (greedy) 3 Process Task 1 Need 3s in [2,5] Time 3 already ON Pick times 4,5 (2 more) 4 Count Active Times Times ON: 2,3,4,5 Active Slots: 2 3 4 5 = 4 FINAL RESULT Computer ON Times: 1 2 3 4 5 = ON = OFF Output: 4 Task Coverage: T0: time 3 (1/1) OK T1: times 3,4,5 (3/3) OK Minimum Time = 4 Key Insight: Greedy scheduling by earliest end time maximizes overlap between tasks. By picking the latest possible times within each task's range, we maximize the chance that subsequent tasks can reuse those active time slots, minimizing total computer ON time. TutorialsPoint - Minimum Time to Complete All Tasks | Greedy Scheduling Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
28.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen