LeetCode in Kotlin

2589. Minimum Time to Complete All Tasks

Hard

There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks where tasks[i] = [starti, endi, durationi] indicates that the ith task should run for a total of durationi seconds (not necessarily continuous) within the inclusive time range [starti, endi].

You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.

Return the minimum time during which the computer should be turned on to complete all tasks.

Example 1:

Input: tasks = [[2,3,1],[4,5,1],[1,5,2]]

Output: 2

Explanation:

Example 2:

Input: tasks = [[1,3,2],[2,5,3],[5,6,2]]

Output: 4

Explanation:

The computer will be on for a total of 4 seconds.

Constraints:

Solution

import java.util.Arrays

class Solution {
    fun findMinimumTime(tasks: Array<IntArray>): Int {
        var res = 0
        val arr = BooleanArray(2001)
        Arrays.sort(tasks) { a: IntArray, b: IntArray ->
            a[1] - b[1]
        }
        for (task in tasks) {
            val start = task[0]
            val end = task[1]
            val dur = task[2]
            var cur = 0
            for (i in start..end) {
                if (arr[i]) {
                    cur++
                }
            }
            if (cur < dur) {
                var i = end
                while (i >= start && cur < dur) {
                    if (!arr[i]) {
                        arr[i] = true
                        res++
                        cur++
                    }
                    i--
                }
            }
        }
        return res
    }
}