Skip to content

Commit 48f07cc

Browse files
committed
to add job seq program
1 parent c9ba5e1 commit 48f07cc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

greedy_methods/job_sequence.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Given a list of tasks, each with a deadline and reward,
3+
The maximum number of tasks that can be scheduled to maximize reward.
4+
We can only complete one task at a time, and each task takes 1 unit
5+
of time to complete. Once a task has passed its deadline, it can no
6+
longer be scheduled.
7+
8+
Example :
9+
tasks_info = [(4, 20), (1, 10), (1, 40), (1, 30)]
10+
max_tasks will return (2, [2, 0]) -
11+
which is by scheduling the tasks with rewards 40, 20
12+
13+
This problem can be solved using the concept of "GREEDY ALGORITHM".
14+
Time Complexity - O(n log n)
15+
16+
We iterate over the tasks array once, sorting it in descending order of
17+
reward. Then we iterate over the sorted tasks array once more, scheduling
18+
each task if its deadline is greater than the current time.The greedy choice
19+
at each point is to either schedule the current task if its deadline is
20+
greater than the current time, or skip it otherwise.
21+
"""
22+
23+
class Task:
24+
def __init__(self, id, deadline, reward):
25+
self.id = id
26+
self.deadline = deadline
27+
self.reward = reward
28+
29+
def max_tasks(tasks_info : list[tuple[int]]) -> int:
30+
"""
31+
>>> max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)])
32+
(2, [2, 0])
33+
>>> max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)])
34+
(2, [3, 2])
35+
"""
36+
tasks = [Task(i, d, p) for i, (d, p) in enumerate(tasks_info)]
37+
38+
tasks.sort(key=lambda task: task.reward, reverse=True)
39+
40+
schedule = []
41+
current_time = 0
42+
43+
for task in tasks:
44+
if task.deadline > current_time:
45+
schedule.append(task.id)
46+
current_time += 1
47+
48+
return len(schedule),schedule
49+
50+
if __name__ == "__main__":
51+
import doctest
52+
doctest.testmod()
53+
54+
print(max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]))

0 commit comments

Comments
 (0)