高级农民
- 积分
- 4019
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-1-22
- 最后登录
- 1970-1-1
|
LC. 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.
Example 1:
Input: tasks = [[1,2],[2,4],[4,8]]
Output: 8
Explanation:
Starting with 8 energy, we finish the tasks in the following order:
- 3rd task. Now energy = 8 - 4 = 4.
- 2nd task. Now energy = 4 - 2 = 2.
- 1st task. Now energy = 2 - 1 = 1.
Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.
Example 2:
Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]
Output: 32
Explanation:
Starting with 32 energy, we finish the tasks in the following order:
- 1st task. Now energy = 32 - 1 = 31.
- 2nd task. Now energy = 31 - 2 = 29.
- 3rd task. Now energy = 29 - 10 = 19.
- 4th task. Now energy = 19 - 10 = 9.
- 5th task. Now energy = 9 - 8 = 1.
Example 3:
Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]
Output: 27
Explanation:
Starting with 27 energy, we finish the tasks in the following order:
- 5th task. Now energy = 27 - 5 = 22.
- 2nd task. Now energy = 22 - 2 = 20.
- 3rd task. Now energy = 20 - 3 = 17.
- 1st task. Now energy = 17 - 1 = 16.
- 4th task. Now energy = 16 - 4 = 12.
- 6th task. Now energy = 12 - 6 = 6.
Constraints:
1 <= tasks.length <= 105
1 <= actuali <= minimumi <= 104
我在写贪心的时候,贪心条件错了,这题最最关键的是贪心的核心,应该是
按 (minimum - actual) 从大到小排序
因为:
一个任务如果 minimum - actual 越大,说明它对“启动时能量”的要求越苛刻,越早做
因为这说明,这个任务,启动条件和真实消耗差距比较大,比如真实只消耗 1 的任务,却需要你的能量储备100;反而 actual 和 minimum 接近说明。你不需要额外能量,可以留到后面再做。
。
这是这题核心贪心结论。
我是贪心和二分,
- class Solution:
- def minimumEffort(self, tasks: List[List[int]]) -> int:
- s_actuals, s_min = 0, 0
- tasks = sorted(tasks, key=lambda x: x[1] - x[0], reverse = True)
-
- for t in tasks:
- s_actuals += t[0]
- s_min += t[1]
-
- def check(energy):
- for t in tasks:
- if energy < t[1]:
- return False
- else:
- energy -= t[0]
- return True
- left, right = s_actuals, s_min
- while left < right:
- mid = (left + right) // 2
- if check(mid):
- right = mid
- else:
- left = mid + 1
- return left
复制代码 但是可以直接贪心!- class Solution:
- def minimumEffort(self, tasks: List[List[int]]) -> int:
- tasks.sort(key=lambda x: x[1] - x[0], reverse=True)
- ans = 0
- energy = 0
- for actual, minimum in tasks:
- if energy < minimum:
- ans += minimum - energy
- energy = minimum
- energy -= actual
- return ans
复制代码 |
|