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 mostsessionTime 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 theminimum 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].
Input: tasks =[1,2,3], sessionTime =3Output: 2Explanation: You can finish the tasks in two work sessions.- First work session: finish the first and the second tasks in1+2=3 hours.- Second work session: finish the third task in3 hours.
Input: tasks =[3,1,3,1,1], sessionTime =8Output: 2Explanation: You can finish the tasks in two work sessions.- First work session: finish all the tasks except the last one in3+1+3+1=8 hours.- Second work session: finish the last task in1 hour.
We want to partition tasks into the minimum number of sessions, each with total time ≤ sessionTime. Try all possible groupings using bitmask DP, where each state represents a subset of tasks.
classSolution {
funminSessions(tasks: IntArray, sessionTime: Int): Int {
val n = tasks.size
val N = 1 shl n
val sum = IntArray(N)
val dp = IntArray(N) { n }
for (mask in1 until N)
for (i in0 until n)
if ((mask shr i) and 1==1) sum[mask] += tasks[i]
dp[0] = 0for (mask in1 until N)
var sub = mask
while (sub > 0) {
if (sum[sub] <= sessionTime)
dp[mask] = minOf(dp[mask], dp[mask xor sub] + 1)
sub = (sub - 1) and mask
}
return dp[N - 1]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defminSessions(self, tasks: list[int], sessionTime: int) -> int:
n = len(tasks)
N =1<< n
sum_mask = [0] * N
dp = [n] * N
for mask in range(1, N):
for i in range(n):
if mask & (1<< i):
sum_mask[mask] += tasks[i]
dp[0] =0for mask in range(1, N):
sub = mask
while sub:
if sum_mask[sub] <= sessionTime:
dp[mask] = min(dp[mask], dp[mask ^ sub] +1)
sub = (sub -1) & mask
return dp[N -1]