Given n jobs where every job has the start time, finish time and profit associated. Find the maximum profit in scheduling jobs such that no two jobs overlap.
Building upon understanding of Weighted interval job scheduling (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def count(jobs): jobs.sort(key = lambda a: a[1]) cache = [0] * len(jobs) cache[0] = jobs[0][2] for i in range(1, len(jobs)): take = jobs[i][2] for j in range(i - 1, -1, -1): if jobs[j][1] <= jobs[i][0]: take += cache[j] break skip = cache[i - 1] cache[i] = max(take, skip) return cache[len(jobs) - 1] data = [ [1, 2, 50], [3, 5, 20], [6, 19, 100], [2, 100, 200] ] print(count(data))
function count(jobs) { jobs.sort((a, b) => a[1] - b[1]); const cache = Array(jobs.length).fill(0); cache[0] = jobs[0][2] for (let i = 1; i < jobs.length; i++) { let take = jobs[i][2]; for (let j = i - 1; j >= 0; j--) { if (jobs[j][1] <= jobs[i][0]) { take += cache[j]; break; } } const skip = cache[i - 1]; cache[i] = Math.max(take, skip); } return cache[jobs.length - 1]; } const data = [ [1, 2, 50], [3, 5, 20], [6, 19, 100], [2, 100, 200] ]; console.log(count(data));