Skip to content

Commit 801d97f

Browse files
committed
Added weighted job scheduling in dp section
1 parent 20e9877 commit 801d97f

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

DP/WeightedJobScheduling/README.md

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Problem:
2+
Given N jobs where every job is represented by following three elements of it.
3+
4+
Start Time
5+
Finish Time
6+
Profit or Value Associated
7+
8+
Find the maximum profit subset of jobs such that no two jobs in the subset overlap.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
struct Job
5+
{
6+
int start, finish, profit;
7+
}jobs[100005];
8+
9+
10+
bool comp(Job a, Job b)
11+
{
12+
return a.finish < b.finish;
13+
}
14+
15+
int binarySearch(int index)
16+
{
17+
int l= 0, h = index - 1;
18+
int ans = -1;
19+
while (l<=h)
20+
{
21+
int m = (l+h)/2;
22+
if (jobs[m].finish <= jobs[index].start)
23+
{
24+
ans = m;
25+
l = m+1;
26+
}
27+
else
28+
h = m-1;
29+
}
30+
return ans;
31+
}
32+
33+
//Main function which computes optimal profit
34+
int weighted_job(int n)
35+
{
36+
37+
sort(jobs, jobs+n, comp);
38+
39+
int dp[n];
40+
41+
dp[0] = jobs[0].profit;
42+
43+
for (int i=1; i<n; i++)
44+
{
45+
dp[i] = jobs[i].profit;
46+
int ind = binarySearch(i);
47+
if (ind != -1)
48+
dp[i]+=dp[ind];
49+
50+
dp[i] = max(dp[i] , dp[i-1]);
51+
}
52+
return dp[n-1];
53+
}
54+
55+
int main()
56+
{
57+
int n; //Number of jobs
58+
cin>>n;
59+
//Enter the jobs start time,finish time and profit of the job.
60+
for(int i = 0;i<n;i++){
61+
cin>>jobs[i].start>>jobs[i].finish>>jobs[i].profit;
62+
}
63+
cout<<"Maximum profit will be "<<weighted_job(n)<<endl;
64+
return 0;
65+
}

0 commit comments

Comments
 (0)