Consider we are given a set of tasks, with startTime, endTime and value. For certain task, startTime <= endTime, indicates task time range [startTime, endTime]
Now we need to choose as many not intersected tasks as possible to maximize the total value of chosen tasks. (Note that endTime is considered in the time range, so [1, 2] and [2, 3] is intersected)
Consider we’ve already known the best solution when only considering time period [t + 1, infty], that is, we already known solution[k] in which k∈[t+1,+∞).
And now, we consider task Ti.
Note
solution[t] here means the maximum sum of value we choose achieve by ONLY selecting tasks that startTime and endTime falls into the range [t, infty].
infty here refers to +∞.
Case1: Choose task Ti
In this case, the task we could choose is:
Task Ti
All the other tasks that need to be chosen to make range [Ti.endTime + 1, infty] reach’s the maximum value solution[Ti.endTime + 1]
the new value sum will be:
solution[i] = Ti.value + solution[Ti.endTime + 1]
Case2: Not Choose task Ti
In this case, since nothing changed compared to previous state, we have:
solution[i] = solution[i + 1]
Sort Task By Time
Notice above, we have one of the state transfer formula:
solution[i] = solution[i + 1]
To ensure solution[i + 1] is the best solution we could found, when processing Ti, all task start later than i must be already considered.
In order to satisfy this, we could sort task by it’s startTime and iterate from the one with largest startTime to the one with smallest startTime. By doing this, when processing Ti with start time t, all tasks that starts later then t will be iterated before, thus, already considered.
Note
The state transfer equation and the iteration above use the direction from the largest startTime to smallest. However, it’s easy to proof that the iteration could goes from the smallest to the largest as well.
In this case, we need to use sort criteria endTime instead of startTime to sort the array, and the state transfer equation should also be modified: