Problem Description
You are given an array of tasks, where each task takes a certain amount of time to complete. You have sessions in which you can work for at most sessionTime hours. Tasks must be finished in the same session in which they are started, though tasks can be completed in any order. The goal is to determine the minimum number of work sessions required to finish all tasks.
Key Insights
- Use bitmasking to represent the state of completed tasks since n ≤ 14.
- Apply recursion with memoization (DP) to explore task assignments.
- Each DP state is represented by a bitmask (indicating tasks done) and the current session’s used time.
- When a task does not fit in the current session, start a new session and update the count.
- The problem can be solved with backtracking combining DP over subsets of tasks.
Space and Time Complexity
Time Complexity: O(2^n * n), where n is the number of tasks. Space Complexity: O(2^n) due to memoization storage.
Solution
We use a dynamic programming approach with bitmasking to represent the subsets of tasks completed. The recursive function dp(mask, timeUsed) returns the number of extra sessions required (beyond an initial session) for a given state. For every state, we try assigning each incomplete task: if it fits into the current session (timeUsed + task[i] ≤ sessionTime), we continue; otherwise, we start a new session and add 1 to our count. By caching results of each state (mask, timeUsed), we prevent redundant calculations, which makes the approach feasible given the constraints.