
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Maximum Profit by Scheduling Jobs in Python
Suppose we have a list of intervals where each interval contains three values [start, end, profit]. We can perform only one task at a time, we have to find the most amount of profit we can get.
So, if the input is like intervals = [[1, 2, 100],[3, 5, 40],[6, 19, 150],[2, 100, 250]], then the output will be 350, as we can take these two intervals [1, 2, 100] and [2, 100, 250]
To solve this, we will follow these steps
- d := an empty map that contains lists as values
- n := 0
- for each (start, end, profit) in intervals, do
- if end > n, then
- n := end
- if end > n, then
- insert pair (start, end) into d[end]
- A := a list of size n + 1 and fill with 0
- for end in range 0 to size of A, do
- if end is in d, then
- for each (start, profit) pair in d[end], do
- A[end] := maximum of A[end], (A[start] + profit) and A[end - 1]
- for each (start, profit) pair in d[end], do
- otherwise,
- A[end] := A[end - 1]
- if end is in d, then
- return last value of A
Example (Python)
Let us see the following implementation to get better understanding −
from collections import defaultdict class Solution: def solve(self, intervals): d = defaultdict(list) n = 0 for start, end, profit in intervals: if end > n: n = end d[end].append([start, profit]) A = [0 for i in range(n + 1)] for end in range(len(A)): if end in d: for start, profit in d[end]: A[end] = max(A[end], A[start] + profit, A[end - 1]) else: A[end] = A[end - 1] return A[-1] ob = Solution() intervals = [[1, 2, 100],[3, 5, 40],[6, 19, 150],[2, 100, 250]] print(ob.solve(intervals))
Input
[[1, 2, 100],[3, 5, 40],[6, 19, 150],[2, 100, 250]]
Output
350
Advertisements