Problem 1665

Abstract / Summary

Find the least starting energy needed so a character can complete all tasks without energy dropping below zero.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1665.py

class Solution:
    def minimumEffort(self, tasks: List[List[int]]) -> int:
        result = 0

        # compute tasks in reverse order of how they will be finished:
        # first compute tasks where there is little overhead
        # that overhead isn't lost, it can be consumed by other tasks
        for actual, minimum in sorted(tasks, key = lambda x : x[1] - x[0]):
            result += actual
            if result < minimum:
                result = minimum

        return result
13 lines | 505 bytes | submitted January 18, 2024 | GitHub   37% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 77% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method minimumEffort that determines the smallest possible cumulative effort required to complete a collection of tasks. Each task is represented by a pair [actual, minimum] where actual is the effort contributed by the task itself and minimum is the required effort level before the task can be started. The algorithm processes the tasks in a specific order that guarantees the final effort never falls below any task’s required threshold, while keeping the total effort as low as possible.

Core Logic

The method begins by initializing a variable that will hold the running total of effort.

result = 0

The next step is to arrange the tasks in an order that facilitates efficient accumulation of effort. The sorting key computes the difference between the required minimum and the actual contribution for each task.

for actual, minimum in sorted(tasks, key=lambda x: x[1] - x[0]):

Processing tasks with a smaller difference first means tasks that add relatively more effort compared to their requirement are handled early, allowing their surplus to satisfy the requirements of later tasks.

Inside the loop the algorithm adds the task’s actual effort to the running total.

result += actual

Immediately after the addition, a check ensures that the running total does not drop below the task’s required minimum. If it does, the total is raised to meet that minimum.

if result < minimum:
    result = minimum

When all tasks have been processed, the final value of result represents the minimal effort needed to satisfy every task’s requirement.

return result

Edge Cases Handled

When a task’s required minimum is larger than the cumulative effort accumulated so far, the conditional adjustment (result = minimum) guarantees that the algorithm never violates the task’s prerequisite. This covers scenarios where a single task demands a high initial effort while contributing little or no additional effort.

If the list of tasks is empty, the initial result value of 0 is returned, correctly indicating that no effort is needed.

When multiple tasks share the same difference between minimum and actual, the stable sorting behavior of Python’s sorted preserves their original relative order, which does not affect correctness because the adjustment step ensures each task’s minimum is respected regardless of tie-breaking.

Performance Optimizations

The primary optimization lies in the choice of sorting key. By ordering tasks based on minimum - actual, the algorithm minimizes the number of times the running total must be raised to meet a task’s requirement. This reduces unnecessary upward adjustments and keeps the cumulative effort as low as possible throughout the iteration.

The loop processes each task exactly once, performing only constant-time arithmetic and a single comparison per iteration. This linear pass over the sorted list ensures that the overall runtime is dominated by the sorting step, which is implemented using Python’s highly optimized Timsort algorithm.

Memory usage is minimal: aside from the input list, only a few scalar variables (result, actual, minimum) are allocated, and the sorted view reuses the original task objects without creating deep copies.

These design choices together provide an efficient solution that scales well with the number of tasks while maintaining a clear and concise implementation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big treasure box, and each task you need to do is like a hungry little robot. Every robot needs a certain amount of energy to start working, and it uses up some energy while it plays. When you put these robots in a special line from the ones that are easiest to satisfy to the ones that are very demanding, you can figure out the smallest amount of energy you need to start with so that every robot gets what it needs. You start with no energy at all and look at the robots one by one. You give the robot its energy and watch it play. If you do not have enough energy for the next robot to start, you just add more energy until you have exactly enough for that robot to turn on. By the time you finish helping all the robots in line, the amount of energy you have collected is the total amount needed to finish everything without any trouble.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.56 | σ = 1.03

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
withaarzoo C++
25 links | 14 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 1 medium 2 hard
5 solutions   January 18, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality