You are given an array tasks where tasks[i] = [actual_i, minimum_i]: - actual_i is the actual amount of energy you spend to finish the i-th task. - minimum_i is the minimum amount of energy you require to begin the i-th 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: Task [4,8] needs 8 energy just to start, and energy never goes up, so we need at least 8. Starting with 8: do [4,8] (8 → 4), then [2,4] (4 → 2), then [1,2] (2 → 1). All tasks finish.
Example 2
Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]
Output: 32
Explanation: Starting with 32: [1,3] leaves 31, [2,4] leaves 29, [10,11] leaves 19, [10,12] leaves 9, and [8,9] needs exactly 9 and leaves 1. With 31, the last task could not be started.
Example 3
Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]
Output: 27
Explanation: The tasks cost 21 in total, and every task needs 6 more than it costs to start. Whichever task is done last must still have that extra 6 available, so we need 21 + 6 = 27. Starting with 27 and doing the tasks from [6,12] down to [1,7] works.
Sort tasks by the gap (minimum - actual) in descending order. Tasks with larger gaps waste more energy on the threshold requirement, so doing them first when energy is highest minimizes the total starting energy needed.
Run checks all cases above. Submit evaluates all test cases.