|
| 1 | +def job_sequencing_with_deadlines(num_jobs: int, jobs: list) -> list: |
| 2 | + """ |
| 3 | + Function to find the maximum profit by doing jobs in a given time frame |
| 4 | +
|
| 5 | + Args: |
| 6 | + num_jobs [int]: Number of jobs |
| 7 | + jobs [list]: A list of tuples of (job_id, deadline, profit) |
| 8 | +
|
| 9 | + Returns: |
| 10 | + max_profit [int]: Maximum profit that can be earned by doing jobs |
| 11 | + in a given time frame |
| 12 | +
|
| 13 | + Examples: |
| 14 | + >>> job_sequencing_with_deadlines(4, |
| 15 | + ... [(1, 4, 20), (2, 1, 10), (3, 1, 40), (4, 1, 30)]) |
| 16 | + [2, 60] |
| 17 | + >>> job_sequencing_with_deadlines(5, |
| 18 | + ... [(1, 2, 100), (2, 1, 19), (3, 2, 27), (4, 1, 25), (5, 1, 15)]) |
| 19 | + [2, 127] |
| 20 | + """ |
| 21 | + |
| 22 | + # Sort the jobs in descending order of profit |
| 23 | + jobs = sorted(jobs, key=lambda value: value[2], reverse=True) |
| 24 | + |
| 25 | + # Create a list of size equal to the maximum deadline |
| 26 | + # and initialize it with -1 |
| 27 | + max_deadline = max(jobs, key=lambda value: value[1])[1] |
| 28 | + time_slots = [-1] * max_deadline |
| 29 | + |
| 30 | + # Finding the maximum profit and the count of jobs |
| 31 | + count = 0 |
| 32 | + max_profit = 0 |
| 33 | + for job in jobs: |
| 34 | + # Find a free time slot for this job |
| 35 | + # (Note that we start from the last possible slot) |
| 36 | + for i in range(job[1] - 1, -1, -1): |
| 37 | + if time_slots[i] == -1: |
| 38 | + time_slots[i] = job[0] |
| 39 | + count += 1 |
| 40 | + max_profit += job[2] |
| 41 | + break |
| 42 | + return [count, max_profit] |
| 43 | + |
| 44 | + |
| 45 | +if __name__ == "__main__": |
| 46 | + import doctest |
| 47 | + |
| 48 | + doctest.testmod() |
0 commit comments