LeetCode in Kotlin

1665. Minimum Initial Energy to Finish Tasks

Hard

You are given an array tasks where tasks[i] = [actuali, minimumi]:

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:

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:

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:

Constraints:

Solution

class Solution {
    fun minimumEffort(tasks: Array<IntArray>): Int {
        tasks.sortWith { a: IntArray, b: IntArray -> a[1] - a[0] - b[1] + b[0] }
        var prev = 0
        for (item in tasks) {
            prev = Math.max(prev + item[0], item[1])
        }
        return prev
    }
}