Problem Description
Given an array of tasks where each task is represented by [start, end, duration], determine the minimum total number of seconds during which a computer must be turned on to complete all tasks. Each task must be executed for a total of “duration” seconds (not necessarily continuous) within its inclusive time window [start, end]. The computer can run any number of tasks concurrently when it is on.
Key Insights
- Sort tasks by their end times so that tasks with earlier deadlines are handled first.
- For each task, count how many seconds have already been scheduled (turned-on) within its time window.
- If additional seconds are needed, schedule them as late as possible (starting from the task's end) to maximize the chance of overlapping with future tasks.
- Use a boolean or integer array (or similar structure) indexed by time to track which seconds have been scheduled.
Space and Time Complexity
Time Complexity: O(n * L) where n is the number of tasks and L is the length of the time range (up to 2000), which is feasible given the constraints. Space Complexity: O(L) for the scheduled time tracker.
Solution
The solution uses a greedy strategy:
- Sort the tasks by their ending time.
- For each task, scan its time interval [start, end] to count the seconds that are already scheduled.
- If the count is less than the required duration, add the missing seconds by scheduling them from the end of the interval backwards. This “late scheduling” ensures that these extra seconds might also serve upcoming tasks.
- Continue until all tasks meet their required durations.
This approach guarantees that the computer is turned on for the minimum necessary time, by efficiently overlapping the running intervals for different tasks.