Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum number of courses we can take based on interval time in Python?
Suppose we have a list of intervals in the form [start, end], representing the start and end time of courses. We need 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 must be after the end of the previous 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]].
Algorithm
To solve this, we will follow these steps ?
- Sort intervals based on ending time
- Initialize counter = 0 and end = -1
- For each interval, if start time is greater than the last end time, select it
- Update counter and end time
Implementation
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))
3
How It Works
The algorithm uses a greedy approach ?
-
Sort by end time:
[[3, 6], [7, 8], [6, 9], [9, 11]] - Select [3, 6]: counter = 1, end = 6
- Select [7, 8]: 7 > 6, so counter = 2, end = 8
- Skip [6, 9]: 6 < 8, overlaps with previous
- Select [9, 11]: 9 > 8, so counter = 3, end = 11
Alternative Approach
Here's a more readable version using direct iteration ?
def max_courses(times):
# Sort by end time
times.sort(key=lambda x: x[1])
courses_taken = 0
last_end_time = -1
for start, end in times:
if start > last_end_time:
courses_taken += 1
last_end_time = end
return courses_taken
# Test the function
times = [[3, 6], [6, 9], [7, 8], [9, 11]]
result = max_courses(times)
print(f"Maximum courses: {result}")
Maximum courses: 3
Conclusion
This problem is solved using a greedy algorithm by sorting intervals by end time and selecting non-overlapping courses. The time complexity is O(n log n) due to sorting, and space complexity is O(1).
