1
1
# Implementation of Weighted Interval Scheduling algorithm
2
- # In this algorithm, we are given a list of jobs with start and end times, and each job has a specific weight.
2
+ # In this algorithm, we are given a list of jobs with start and end times,
3
+ # and each job has a specific weight.
3
4
# The goal is to find the maximum weight subset of non-overlapping jobs.
4
- # https://en.wikipedia.org/wiki/Interval_scheduling#:~:text=their%20finishing%20times.-,Weighted,-%5Bedit%5D
5
+ # https://en.wikipedia.org/wiki/Interval_scheduling
5
6
6
7
from __future__ import annotations
7
8
8
9
9
10
def latest_non_conflict (jobs : list [tuple [int , int , int ]], n : int ) -> int :
10
11
"""
11
- This function finds the latest job that does not conflict with the current job at index `n`.
12
- The jobs are given as (start_time, end_time, weight), and the jobs should be sorted by end time.
13
- It returns the index of the latest job that finishes before the current job starts.
12
+ This function finds the latest job that does not conflict with
13
+ the current job at index `n`.
14
+ The jobs are given as (start_time, end_time, weight), and the
15
+ jobs should be sorted by end time.
16
+ It returns the index of the latest job that finishes before the
17
+ current job starts.
14
18
Return: The index of the latest non-conflicting job.
15
19
>>> latest_non_conflict([(1, 3, 50), (2, 5, 20), (4, 6, 30)], 2)
16
20
0
@@ -25,9 +29,11 @@ def latest_non_conflict(jobs: list[tuple[int, int, int]], n: int) -> int:
25
29
26
30
def find_max_weight (jobs : list [tuple [int , int , int ]]) -> int :
27
31
"""
28
- This function calculates the maximum weight of non-overlapping jobs using dynamic programming.
32
+ This function calculates the maximum weight of non-overlapping jobs
33
+ using dynamic programming.
29
34
Each job is represented by a tuple (start_time, end_time, weight).
30
- The function builds a DP table where each entry `dp[i]` represents the maximum weight achievable
35
+ The function builds a DP table where each entry `dp[i]` represents
36
+ the maximum weight achievable
31
37
using jobs from index 0 to i.
32
38
Return: The maximum achievable weight without overlapping jobs.
33
39
>>> find_max_weight([(1, 3, 50), (2, 5, 20), (4, 6, 30)])
@@ -52,7 +58,8 @@ def find_max_weight(jobs: list[tuple[int, int, int]]) -> int:
52
58
if latest_job != - 1 :
53
59
include_weight += dp [latest_job ]
54
60
55
- # Exclude the current job, and take the maximum of including or excluding
61
+ # Exclude the current job, and take the maximum of including or
62
+ # excluding
56
63
dp [i ] = max (include_weight , dp [i - 1 ])
57
64
58
65
return dp [- 1 ] # The last entry contains the maximum weight
0 commit comments