Skip to main content
Back to problems
#2589
Hard Algorithms

Minimum time to complete all tasks

Array Binary Search Stack Greedy Sorting
39.7% acceptance
Feb 25, 2026
462
21
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_minimum_time(mut tasks: Vec<Vec<i32>>) -> i32 {
    // Sort tasks by end time (greedy: process tasks with earlier deadlines first).
    // Use a boolean array to track which time slots have the computer on.
    // For each task, count already-active slots in [start, end],
    // then fill remaining needed slots from the right end of [start, end].
    tasks.sort_unstable_by_key(|t| t[1]);
    let max_time = 2001usize;
    let mut on = vec![false; max_time + 1];
    for t in &tasks {
      let (s, e, mut d) = (t[0] as usize, t[1] as usize, t[2] as usize);
      // Count already-on slots in [s, e]
      let already: usize = (s..=e).filter(|&i| on[i]).count();
      if already >= d {
        continue;
      }
      d -= already;
      // Fill d slots from right to left in [s, e]
      let mut j = e as isize;
      while d > 0 && j >= s as isize {
        if !on[j as usize] {
          on[j as usize] = true;
          d -= 1;
        }
        j -= 1;
      }
    }
    on.iter().filter(|&&v| v).count() as i32
  }
}