#1665

Minimum Initial Energy to Finish Tasks

Hard
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach sorts the tasks based on their minimum energy requirement and calculates the necessary initial energy using a greedy strategy. This ensures we always have enough energy to complete the tasks in the best order.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the tasks based on their minimum energy requirement.
  2. 2Step 2: Initialize current energy and required energy to 0.
  3. 3Step 3: Iterate through the sorted tasks, updating current energy and checking if it meets the minimum requirement.
  4. 4Step 4: If current energy is less than the minimum required for a task, calculate the additional energy needed and update the required energy.
solution.py13 lines
1# Full working Python code
2
3def minimum_initial_energy(tasks):
4    tasks.sort(key=lambda x: x[1])
5    current_energy = 0
6    required_energy = 0
7    for actual, minimum in tasks:
8        required_energy = max(required_energy, minimum - current_energy)
9        current_energy += actual
10    return required_energy
11
12tasks = [[1,2],[2,4],[4,8]]
13print(minimum_initial_energy(tasks))

Complexity note: The sorting step takes O(n log n), and the subsequent single pass through the tasks is O(n), making this approach efficient overall.

  • 1Sorting tasks by their minimum energy requirement allows for a more efficient greedy approach.
  • 2The relationship between actual and minimum energy spent is crucial for determining the required initial energy.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.