Suppose, we have three lists whose lengths are same. These are deadlines, credits, and durations. They are representing course assignments. For the i−th assignment deadlines[i] shows its deadline, credits[i] shows its credit, and durations[i] shows the number of days it takes to finish the assignment. One assignment must be completed before starting another one. We have to keep in mind that we can complete an assignment on the day it's due and we are currently on the start of day 0.
So, if the input is like, deadlines = [7, 5, 10], credits = [8, 7, 10], durations = [5, 4, 10], then the output will be 10.
To solve this, we will follow these steps −
jobs := sort the list zip(deadlines, durations, credits)
Define a function dp().
if i >= size of jobs , then
ans := dp(i + 1, day)
deadline, duration, credit := jobs[i]
if day + duration − 1 <= deadline, then
ans := maximum of ans, dp(i + 1, day + duration) + credit
From the main method return dp(0, 0)
Let us see the following implementation to get better understanding −
class Solution: def solve(self, deadlines, credits, durations): jobs = sorted(zip(deadlines, durations, credits)) def dp(i=0, day=0): if i >= len(jobs): return 0 ans = dp(i + 1, day) deadline, duration, credit = jobs[i] if day + duration − 1 <= deadline: ans = max(ans, dp(i + 1, day + duration) + credit) return ans return dp() ob = Solution() deadlines = [7, 5, 10] credits = [8, 7, 10] durations = [5, 4, 10] print(ob.solve(deadlines, credits, durations))
[7, 5, 10], [8, 7, 10], [5, 4, 10]