
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
Find Minimum Number of Buses Required to Pass Through All Stops in Python
Suppose we have a list of numbers called nums and that is showing the bus stops on a line where nums[i] shows the time a bus must arrive at station i. Now that buses can only move forward, we have to find the minimum number of buses that are needed to pass through all the stops.
So, if the input is like nums = [1, 2, 7, 9, 3, 4], then the output will be 2, as one bus can take stops [1, 2, 3, 4] and another can do [7, 9].
To solve this, we will follow these steps−
ans := 0
seen := a list whose length is same as nums and initially filled with false
-
for each index i and corresponding n in nums, do
-
if seen[i] is false, then
seen[i] := True
ans := ans + 1
prev := n
-
for j in range i+1 to size of nums, do
-
if nums[j] > prev and seen[j] is false, then
seen[j] := True
prev := nums[j]
-
-
return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): ans = 0 seen = [False] * len(nums) for i, n in enumerate(nums): if not seen[i]: seen[i] = True ans += 1 prev = n for j in range(i+1, len(nums)): if nums[j] > prev and not seen[j]: seen[j] = True prev = nums[j] return ans ob = Solution() nums = [1, 2, 7, 9, 3, 4] print(ob.solve(nums))
Input
[1, 2, 7, 9, 3, 4]
Output
2