Greedy Task Energy Minimization
IntuitionTo minimize the initial energy needed to complete all tasks, we should order the tasks in a way that avoids having to "top up" energy unnecessarily. Ta
# Intuition
To minimize the initial energy needed to complete all tasks, we should order the tasks in a way that avoids having to "top up" energy unnecessarily. Tasks that have a large gap between the required minimum energy and actual effort are more restrictive and should be prioritized earlier.

# Approach
1. Sort the tasks in descending order based on the difference between minimum energy required and actual effort (i.e., `min - effort`).
2. Initialize `total_effort` and `current_energy` to 0.
3. Loop through the sorted tasks:
   - If `current_energy` is less than the task's minimum required energy, increase it and add the difference to `total_effort`.
   - Deduct the task’s effort from `current_energy`.
4. Return the total energy added (`total_effort`) as the final answer.


# Complexity
- Time complexity:  
  $$O(n \log n)$$ — due to sorting the tasks.

- Space complexity:  
  $$O(1)$$ — only a constant amount of space is used (no extra data structures).


# Code
```python3 
class Solution:
    def minimumEffort(self, tasks: list[list[int]]) -> int:
        tasks.sort(key=lambda x: x[1] - x[0], reverse=True)
        
        total_effort = 0
        current_energy = 0
        
        for effort, minimum in tasks:
            if current_energy < minimum:
                total_effort += minimum - current_energy
                current_energy = minimum
            current_energy -= effort
        
        return total_effort

```



# Thanks for reading <3


![image.png](https://assets.leetcode.com/users/images/0eff8d12-ac0f-4e91-a312-4a940e78f2ac_1743969942.5589492.png)

['Python3']