[LeetCode] Minimum Initial Energy to Finish Tasks

1665. Minimum Initial Energy to Finish Tasks

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.

For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.

You can finish the tasks in any order you like.

Return the minimum initial amount of energy you will need to finish all the tasks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int minimumEffort(vector<vector<int>>& A) {
sort(begin(A), end(A), [](vector<int>&a, vector<int>& b) {
int ad = a[1] - a[0], bd = b[1] - b[0];
if(ad == bd)
return a[1] > b[1];
return ad > bd;
});

int res = 0, cur = 0;
for(auto& t : A) {
int req = t[1], use = t[0];

if(cur < req) {
res += (req - cur);
cur = req - use;
} else {
cur = cur - use;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/02/PS/LeetCode/minimum-initial-energy-to-finish-tasks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.