Program to find maximum number of courses we can take based on interval time in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a list of intervals in the form [start, end], this is representing the start and end time of a course. We have to find the maximum number of courses we can take, assuming we can only take one course at a time and the start of a course needs to be later than the end of the last course.

So, if the input is like times = [[3, 6],[6, 9],[7, 8],[9, 11]], then the output will be 3, as we can take courses [[3, 6], [7, 8], [9, 11]]

To solve this, we will follow these steps:

• sort time based on ending time

• counter := 0, end := -1

• for i in range 0 to size of times, do

• if times[i, 0] > end is non-zero, then

• counter := counter + 1

• end := times[i, 1]

• return counter

Let us see the following implementation to get better understanding:

Example

Live Demo

class Solution:
def solve(self, times):
times.sort(key=lambda x: x[1])

counter = 0
end = -1

for i in range(len(times)):
if times[i][0] > end:
counter += 1
end = times[i][1]
return counter

ob = Solution()
times = [
[3, 6],
[6, 9],
[7, 8],
[9, 11]
]
print(ob.solve(times))

Input

[ [3, 6],[6, 9],[7, 8],[9, 11]]

Output

3
Published on 10-Nov-2020 08:24:08