HardNo. 1665

Minimum Initial Energy to Finish Tasks — LeetCode 1665 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Sorting
Reading time
2 min

The problem

You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task.

Example

Input
tasks = [[1,2],[2,4],[4,8]]
Output
8
Explanation
Starting with 8 energy, we finish the tasks in the following order:

Python solution

PythonSolution
class Solution:
    def minimumEffort(self, tasks: List[List[int]]) -> int:
        ans = cur = 0
        for a, m in sorted(tasks, key=lambda x: x[0] - x[1]):
            if cur < m:
                ans += m - cur
                cur = m
            cur -= a
        return ans

Complexity

Time
O(n × log n)where n is the number of tasks
Space · auxiliary
O(1)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1665. Minimum Initial Energy to Finish Tasks is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0452Minimum Number of Arrows to Burst BalloonsMedium
0455Assign CookiesEasy
0502IPOHard
0561Array PartitionEasy

Frequently asked questions

How hard is LeetCode 1665. Minimum Initial Energy to Finish Tasks?

LeetCode 1665. Minimum Initial Energy to Finish Tasks is rated Hard on LeetCode.

What is the time complexity of LeetCode 1665. Minimum Initial Energy to Finish Tasks?

The Python solution on this page runs in O(n × log n), where n is the number of tasks.

What is the space complexity of LeetCode 1665. Minimum Initial Energy to Finish Tasks?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 1665. Minimum Initial Energy to Finish Tasks cover?

LeetCode 1665. Minimum Initial Energy to Finish Tasks is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.