Skip to main content
Back to problems
#1665
Hard Algorithms

Minimum initial energy to finish tasks

Array Greedy Sorting
60.7% acceptance
Feb 25, 2026
615
40
You are given an array tasks where tasks[i] = [actual_i, minimum_i]: actual_i is the actual amount of energy you spend to finish task i. minimum_i is the minimum amount of energy you require to begin task i. Return the minimum initial amount of energy you will need to finish all tasks.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_effort(mut tasks: Vec<Vec<i32>>) -> i32 {
    // Greedy: sort by (minimum - actual) descending (larger buffer tasks go first)
    tasks.sort_unstable_by(|a, b| {
      (b[1] - b[0]).cmp(&(a[1] - a[0]))
    });
    let mut ans = 0i32;
    let mut energy_used = 0i32; // sum of actuals processed so far
    for task in &tasks {
      let (actual, minimum) = (task[0], task[1]);
      ans = ans.max(energy_used + minimum);
      energy_used += actual;
    }
    ans
  }
}