Minimum Time to Complete All Tasks Problem
Description
LeetCode Problem 2589.
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] = [start_i, end_i, duration_i] indicates that the i^th task should run for a total of duration_i seconds (not necessarily continuous) within the inclusive time range [start_i, end_i].
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.
Example 1:
Input: tasks = [[2,3,1],[4,5,1],[1,5,2]]
Output: 2
Explanation:
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
Example 2:
Input: tasks = [[1,3,2],[2,5,3],[5,6,2]]
Output: 4
Explanation:
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
Constraints:
1 <= tasks.length <= 2000tasks[i].length == 31 <= start_i, end_i <= 20001 <= duration_i <= end_i - start_i + 1
Solution
Approach: Greedy + Sorting
Each task needs duration chosen time points inside [start, end], and we want to minimize the number of distinct time points chosen overall.
Sort the tasks by end. For each task, first count how many already chosen points lie in [start, end] and subtract them from duration. Then choose the missing points as late as possible, scanning from end backwards, because late points are the most likely to be shared by later tasks (which have later ends). An array vis of size 2010 marks the chosen points, and the answer is their total.
The time complexity is O(n log n + n * m) and the space complexity is O(m), where m = 2010 is the time range.
class Solution:
def findMinimumTime(self, tasks: List[List[int]]) -> int:
tasks.sort(key=lambda x: x[1])
vis = [0] * 2010
ans = 0
for start, end, duration in tasks:
duration -= sum(vis[start : end + 1])
i = end
while i >= start and duration > 0:
if not vis[i]:
duration -= 1
vis[i] = 1
ans += 1
i -= 1
return ans