Minimum Initial Energy to Finish Tasks — LeetCode 1665 Python Solution
- Problem
- #1665
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n\times \log n), where n is the number of tasks |
| Space | O(1) auxiliary |
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
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\times \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.