Minimum Number of Work Sessions to Finish the Tasks Problem
Description
LeetCode Problem 1986.
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the i^th 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:
- If you start a task in a work session, you must complete it in the same work session.
- You can start a new task immediately after finishing the previous one.
- You may complete the tasks in any order.
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.
- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.
- Second work session: finish the third task in 3 hours.
Example 2:
Input: tasks = [3,1,3,1,1], sessionTime = 8
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.
- Second work session: finish the last task in 1 hour.
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:
n == tasks.length1 <= n <= 141 <= tasks[i] <= 10max(tasks[i]) <= sessionTime <= 15
Solution
Approach: Bitmask DP + Subset Enumeration
There are at most 14 tasks, so a set of tasks can be a bitmask. First mark every mask ok[mask] whose total time fits into one session. Then let f[mask] be the fewest sessions needed for the tasks in mask: try every non-empty subset sub of mask with ok[sub] as the last session, and take f[mask ^ sub] + 1. The answer is f of the mask with all tasks.
Enumerating all subsets of every mask costs 3^n in total.
Complexity: time O(3^n), space O(2^n).
from math import inf
class Solution:
def minSessions(self, tasks: List[int], sessionTime: int) -> int:
n = len(tasks)
ok = [False] * (1 << n)
for i in range(1, 1 << n):
t = sum(tasks[j] for j in range(n) if i >> j & 1)
ok[i] = t <= sessionTime
f = [inf] * (1 << n)
f[0] = 0
for i in range(1, 1 << n):
j = i
while j:
if ok[j]:
f[i] = min(f[i], f[i ^ j] + 1)
j = (j - 1) & i
return f[-1]