[LeetCode] Course Schedule III

630. Course Schedule III

There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.

You will start on the 1st day and you cannot take two or more courses simultaneously.

Return the maximum number of courses that you can take.

  • heap + greedy solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int scheduleCourse(vector<vector<int>>& A) {
sort(begin(A), end(A), [](auto& a, auto& b){
return a[1] < b[1];
});
priority_queue<int> pq;
int sum = 0;
for(auto& a : A) {
auto d = a[0], l = a[1];
sum += d;
pq.push(d);
if(sum > l) {
sum -= pq.top();
pq.pop();
}
}
return pq.size();
}
};
  • knapsack solution (TLE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int scheduleCourse(vector<vector<int>>& A) {
sort(begin(A), end(A), [](auto& a, auto& b){
return a[1] < b[1];
});
int dp[10001] = {}, res = 0;
dp[0] = 1;
for(auto& a : A) {
int d = a[0], l = a[1];
if(d > l) continue;
for(int i = l; i >= d; i--) {
if(dp[i-d])
res = max(res, dp[i] = max(dp[i], dp[i-d] + 1));
}
}
return max(0, res - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/08/PS/LeetCode/course-schedule-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.