Skip to content

Commit 44d33c4

Browse files
authored
Create job_scheduling.py
Weighted Job Scheduling in O(n Log n) time
1 parent 8605aa8 commit 44d33c4

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

dp/job_scheduling.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Python program for weighted job scheduling using Dynamic
2+
# Programming and Binary Search
3+
4+
# Class to represent a job
5+
class Job:
6+
def __init__(self, start, finish, profit):
7+
self.start = start
8+
self.finish = finish
9+
self.profit = profit
10+
11+
12+
# A Binary Search based function to find the latest job
13+
# (before current job) that doesn't conflict with current
14+
# job. "index" is index of the current job. This function
15+
# returns -1 if all jobs before index conflict with it.
16+
# The array jobs[] is sorted in increasing order of finish
17+
# time.
18+
def binarySearch(job, start_index):
19+
20+
# Initialize 'lo' and 'hi' for Binary Search
21+
lo = 0
22+
hi = start_index - 1
23+
24+
# Perform binary Search iteratively
25+
while lo <= hi:
26+
mid = (lo + hi) // 2
27+
if job[mid].finish <= job[start_index].start:
28+
if job[mid + 1].finish <= job[start_index].start:
29+
lo = mid + 1
30+
else:
31+
return mid
32+
else:
33+
hi = mid - 1
34+
return -1
35+
36+
# The main function that returns the maximum possible
37+
# profit from given array of jobs
38+
def schedule(job):
39+
40+
# Sort jobs according to finish time
41+
job = sorted(job, key = lambda j: j.finish)
42+
43+
# Create an array to store solutions of subproblems. table[i]
44+
# stores the profit for jobs till arr[i] (including arr[i])
45+
n = len(job)
46+
table = [0 for _ in range(n)]
47+
48+
table[0] = job[0].profit;
49+
50+
# Fill entries in table[] using recursive property
51+
for i in range(1, n):
52+
53+
# Find profit including the current job
54+
inclProf = job[i].profit
55+
l = binarySearch(job, i)
56+
if (l != -1):
57+
inclProf += table[l];
58+
59+
# Store maximum of including and excluding
60+
table[i] = max(inclProf, table[i - 1])
61+
62+
return table[n-1]

0 commit comments

Comments
 (0)