Skip to content

Commit 147c3ac

Browse files
Merge pull request #1 from Johnaaron0108/Johnaaron0108-patch-1
Create job_scheduling.py
2 parents 788d95b + 52d1eca commit 147c3ac

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Weighted Job Scheduling Problem
3+
Given jobs with start time, end time, and profit, find the maximum profit
4+
subset of non-overlapping jobs.
5+
"""
6+
7+
from bisect import bisect_right
8+
9+
def job_scheduling(jobs):
10+
"""
11+
>>> jobs = [(1, 3, 50), (3, 5, 20), (0, 6, 100), (4, 6, 70), (3, 8, 60)]
12+
>>> job_scheduling(jobs)
13+
120
14+
>>> jobs = [(1, 2, 50), (3, 5, 20), (6, 19, 100), (2, 100, 200)]
15+
>>> job_scheduling(jobs)
16+
250
17+
"""
18+
# Sort jobs by end time
19+
jobs.sort(key=lambda x: x[1])
20+
n = len(jobs)
21+
# dp[i] stores max profit including jobs[i]
22+
dp = [0] * n
23+
dp[0] = jobs[0][2]
24+
25+
# Store end times separately for binary search
26+
end_times = [job[1] for job in jobs]
27+
28+
for i in range(1, n):
29+
profit_incl = jobs[i][2]
30+
# Find last non-conflicting job using binary search
31+
index = bisect_right(end_times, jobs[i][0]-1) - 1
32+
if index != -1:
33+
profit_incl += dp[index]
34+
dp[i] = max(profit_incl, dp[i-1])
35+
return dp[-1]
36+
37+
38+
if __name__ == "__main__":
39+
import doctest
40+
doctest.testmod()

0 commit comments

Comments
 (0)