|
| 1 | +/** |
| 2 | + * 1986. Minimum Number of Work Sessions to Finish the Tasks |
| 3 | + * https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are n tasks assigned to you. The task times are represented as an integer array tasks of |
| 7 | + * length n, where the ith task takes tasks[i] hours to finish. A work session is when you work |
| 8 | + * for at most sessionTime consecutive hours and then take a break. |
| 9 | + * |
| 10 | + * You should finish the given tasks in a way that satisfies the following conditions: |
| 11 | + * - If you start a task in a work session, you must complete it in the same work session. |
| 12 | + * - You can start a new task immediately after finishing the previous one. |
| 13 | + * - You may complete the tasks in any order. |
| 14 | + * |
| 15 | + * Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the |
| 16 | + * tasks following the conditions above. |
| 17 | + * |
| 18 | + * The tests are generated such that sessionTime is greater than or equal to the maximum element |
| 19 | + * in tasks[i]. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} tasks |
| 24 | + * @param {number} sessionTime |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var minSessions = function(tasks, sessionTime) { |
| 28 | + const n = tasks.length; |
| 29 | + const dp = new Array(1 << n).fill(n + 1); |
| 30 | + dp[0] = 0; |
| 31 | + |
| 32 | + for (let mask = 1; mask < 1 << n; mask++) { |
| 33 | + let time = 0; |
| 34 | + for (let i = 0; i < n; i++) { |
| 35 | + if (mask & (1 << i)) { |
| 36 | + time += tasks[i]; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + for (let subset = mask; subset; subset = (subset - 1) & mask) { |
| 41 | + if (subset === mask) continue; |
| 42 | + let subsetTime = 0; |
| 43 | + for (let i = 0; i < n; i++) { |
| 44 | + if (subset & (1 << i)) { |
| 45 | + subsetTime += tasks[i]; |
| 46 | + } |
| 47 | + } |
| 48 | + if (subsetTime <= sessionTime) { |
| 49 | + dp[mask] = Math.min(dp[mask], dp[mask ^ subset] + 1); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if (time <= sessionTime) { |
| 54 | + dp[mask] = 1; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return dp[(1 << n) - 1]; |
| 59 | +}; |
0 commit comments