LeetCode in Kotlin

1986. Minimum Number of Work Sessions to Finish the Tasks

Medium

There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.

You should finish the given tasks in a way that satisfies the following conditions:

Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.

The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].

Example 1:

Input: tasks = [1,2,3], sessionTime = 3

Output: 2

Explanation: You can finish the tasks in two work sessions.

Example 2:

Input: tasks = [3,1,3,1,1], sessionTime = 8

Output: 2

Explanation: You can finish the tasks in two work sessions.

Example 3:

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

Output: 1

Explanation: You can finish all the tasks in one work session.

Constraints:

Solution

class Solution {
    fun minSessions(tasks: IntArray, sessionTime: Int): Int {
        val len = tasks.size
        // minimum, all tasks can fit into 1 session
        var i = 1
        // maximum, each task take 1 session to finish
        var j = len
        while (i < j) {
            // try m sessions to see whether it can work
            val m = (i + j) / 2
            if (canFit(tasks, IntArray(m), sessionTime, len - 1)) {
                j = m
            } else {
                i = m + 1
            }
        }
        return i
    }

    private fun canFit(tasks: IntArray, sessions: IntArray, sessionTime: Int, idx: Int): Boolean {
        // all tasks have been taken care of
        if (idx == -1) {
            return true
        }
        val dup: MutableSet<Int> = HashSet()
        // now to take care of tasks[idx]
        // try each spot
        for (i in sessions.indices) {
            // current spot cannot fit
            if (sessions[i] + tasks[idx] > sessionTime || dup.contains(sessions[i] + tasks[idx])) {
                continue
            }
            dup.add(sessions[i] + tasks[idx])
            sessions[i] += tasks[idx]
            if (canFit(tasks, sessions, sessionTime, idx - 1)) {
                return true
            }
            sessions[i] -= tasks[idx]
        }
        return false
    }
}