[LeetCode] Minimum Number of Work Sessions to Finish the Tasks

1986. Minimum Number of Work Sessions to Finish the Tasks

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:

  • 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].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
map<int, pair<int, int>> sessions;
bool compare(int bitMask, pair<int, int> session) {
if(!sessions.count(bitMask)) return true;

return sessions[bitMask].first == session.first ? sessions[bitMask].second > session.second : sessions[bitMask].first > session.first;
}
pair<int, int> nextSession(pair<int, int> session, int val, int st) {
if(val == st) return {session.first + 1, session.second};
if(session.second + val > st) return {session.first + 1, val};
return {session.first + (session.second + val) / st, (session.second + val) % st};
}
int dfs(vector<int>& t, int st, int choose = 0, pair<int, int> session = {}) {
if(!compare(choose, session)) return sessions[(1<<t.size()) - 1].first + (sessions[(1<<t.size()) - 1].second != 0);
sessions[choose] = session;

for(int i = 0; i < t.size(); i++) {
if(choose & (1 << i)) continue;

dfs(t, st, choose | (1<<i), nextSession(session, t[i], st));
}
return sessions[(1<<t.size()) - 1].first + (sessions[(1<<t.size()) - 1].second != 0);
}
public:
int minSessions(vector<int>& tasks, int sessionTime) {
return dfs(tasks, sessionTime);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/19/PS/LeetCode/minimum-number-of-work-sessions-to-finish-the-tasks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.