First, we sort courses by the end date, this way, when we're iterating through the courses, we can switch out any previous course with the current one without worrying about end date.

Next, we iterate through each course, if we have enough days, we'll add it to our multiset. If we don't have enough days, then we can either ignore this course, or we can use it to replace a longer course we added earlier.

```
class Solution {
public:
int scheduleCourse(vector<vector<int>>& courses) {
// sort courses by the end date
sort(courses.begin(),courses.end(),
[](vector<int> a, vector<int> b){return a.back()<b.back();});
multiset<int> cls; // store lengths of each course we take (could be duplicates!)
int cursum=0;
for (int i=0; i<courses.size(); i++) {
// if we have enough time, we will take this course
if (cursum+courses[i].front()<=courses[i].back()) {
cls.insert(courses[i].front());
cursum+=courses[i].front();
} else if (*cls.rbegin()>courses[i].front()) {
// if we don't have enough time, we switch out a longer course
cursum+=courses[i].front()-*cls.rbegin();
cls.erase(--cls.end());
cls.insert(courses[i].front());
} // if we don't have enough time for course[i],
//and it's longer than any courses taken, then we ignore it
}
return cls.size();
}
};
```

My final consideration was when we replace a longer course with a much shorter one, does that mean we'll have enough room to take some courses previously ignored for being too long?

The answer is no, because any courses we missed would be longer than what's in multiset `cls`

. So the increase in number of days cannot be larger than the largest element in `cls`

, and certainly will be less than a previously ignored course which has to be even longer.