|
| 1 | +""" |
| 2 | +Given a list of tasks, each with a deadline and reward, calculate which tasks can be |
| 3 | +completed to yield the maximum reward. Each task takes one unit of time to complete, |
| 4 | +and we can only work on one task at a time. Once a task has passed its deadline, it |
| 5 | +can no longer be scheduled. |
| 6 | +
|
| 7 | +Example : |
| 8 | +tasks_info = [(4, 20), (1, 10), (1, 40), (1, 30)] |
| 9 | +max_tasks will return (2, [2, 0]) - |
| 10 | +Scheduling these tasks would result in a reward of 40 + 20 |
| 11 | +
|
| 12 | +This problem can be solved using the concept of "GREEDY ALGORITHM". |
| 13 | +Time Complexity - O(n log n) |
| 14 | +https://medium.com/@nihardudhat2000/job-sequencing-with-deadline-17ddbb5890b5 |
| 15 | +""" |
| 16 | +from dataclasses import dataclass |
| 17 | +from operator import attrgetter |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class Task: |
| 22 | + task_id: int |
| 23 | + deadline: int |
| 24 | + reward: int |
| 25 | + |
| 26 | + |
| 27 | +def max_tasks(tasks_info: list[tuple[int, int]]) -> list[int]: |
| 28 | + """ |
| 29 | + Create a list of Task objects that are sorted so the highest rewards come first. |
| 30 | + Return a list of those task ids that can be completed before i becomes too high. |
| 31 | + >>> max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]) |
| 32 | + [2, 0] |
| 33 | + >>> max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) |
| 34 | + [3, 2] |
| 35 | + >>> max_tasks([(9, 10)]) |
| 36 | + [0] |
| 37 | + >>> max_tasks([(-9, 10)]) |
| 38 | + [] |
| 39 | + >>> max_tasks([]) |
| 40 | + [] |
| 41 | + >>> max_tasks([(0, 10), (0, 20), (0, 30), (0, 40)]) |
| 42 | + [] |
| 43 | + >>> max_tasks([(-1, 10), (-2, 20), (-3, 30), (-4, 40)]) |
| 44 | + [] |
| 45 | + """ |
| 46 | + tasks = sorted( |
| 47 | + ( |
| 48 | + Task(task_id, deadline, reward) |
| 49 | + for task_id, (deadline, reward) in enumerate(tasks_info) |
| 50 | + ), |
| 51 | + key=attrgetter("reward"), |
| 52 | + reverse=True, |
| 53 | + ) |
| 54 | + return [task.task_id for i, task in enumerate(tasks, start=1) if task.deadline >= i] |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + import doctest |
| 59 | + |
| 60 | + doctest.testmod() |
| 61 | + print(f"{max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]) = }") |
| 62 | + print(f"{max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) = }") |
0 commit comments