Minimum Initial Energy to Finish Tasks - Problem

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 the i-th task.
  • minimum_i is the minimum amount of energy you require to begin the i-th task.

For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.

You can finish the tasks in any order you like.

Return the minimum initial amount of energy you will need to finish all the tasks.

Input & Output

Example 1 — Basic Case
$ Input: tasks = [[1,2],[2,4],[4,8]]
Output: 8
💡 Note: Starting with 8 energy: complete [4,8] (8≥8, energy=4), then [2,4] (4≥4, energy=2), then [1,2] (2≥2, energy=1)
Example 2 — Equal Requirements
$ Input: tasks = [[1,3],[2,4],[10,11]]
Output: 32
💡 Note: Optimal order after sorting by overhead: [1,3], [2,4], [10,11]. Working backwards: need 11, then max(4,11+2)=13, then max(3,13+1)=14. But we need to check the reverse calculation properly.
Example 3 — Minimum Case
$ Input: tasks = [[1,1]]
Output: 1
💡 Note: Only one task with minimum energy 1, so initial energy needed is 1

Constraints

  • 1 ≤ tasks.length ≤ 105
  • 1 ≤ actuali ≤ minimumi ≤ 104

Visualization

Tap to expand
Minimum Initial Energy to Finish TasksInput Tasks[1, 3]overhead: 2[2, 2]overhead: 0Sorted Order[1, 3] firsthigher overhead[2, 2] secondlower overheadWork backwards: need 2 → need max(3, 2+1) = 3 → need max(2, 3+2) = 5Minimum Initial Energy = 5Greedy approach ensures optimal energy management
Understanding the Visualization
1
Input Tasks
Each task has [actual_energy, minimum_energy] requirements
2
Optimal Ordering
Sort by energy overhead (minimum - actual) descending
3
Calculate Energy
Work backwards to find minimum initial energy
Key Takeaway
🎯 Key Insight: Tasks with higher energy overhead must be done first to minimize initial energy
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~25 min Avg. Time
485 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