Minimum Cars for Group Trip

Moderate
0/80
0 upvote
Asked in company
FactSet

Problem statement

You are organizing a group trip and need to transport everyone using a fleet of available cars. You are given the total number of people who need to travel and a list of the seating capacities of the cars you have.

Your task is to determine the minimum number of cars required to transport all the people.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer 'P', the total number of people to transport.

The second line contains an integer 'C', the number of cars available.

The third line contains 'C' space-separated integers, representing the seating capacity of each car.


Output Format:
Print a single integer representing the minimum number of cars required.


Note:
It is guaranteed that the total capacity of all cars is sufficient to accommodate all the people.

The key to this problem is a greedy strategy: to use the fewest cars, you should always pick the available cars with the largest capacities first.
Sample Input 1:
10
4
5 2 4 3


Sample Output 1:
3


Explanation for Sample 1:
Total people to transport: 10.
Available car capacities: `{5, 2, 4, 3}`.
To minimize the number of cars, we use the largest ones first:
1.  Use the car with capacity 5. People remaining: `10 - 5 =     5`. (1 car used)
2.  Use the next largest car, capacity 4. People remaining: `5 - 4 = 1`. (2 cars used)
3.  Use the next largest car, capacity 3, to transport the last person. (3 cars used)
A minimum of 3 cars are required.


Sample Input 2:
25
3
10 10 10


Sample Output 2:
3


Explanation for Sample 2:
Total people: 25.
Car capacities: `{10, 10, 10}`.
1.  Use car 1 (capacity 10). People remaining: 15.
2.  Use car 2 (capacity 10). People remaining: 5.
3.  Use car 3 (capacity 10).
All 3 cars are required.


Expected Time Complexity:
The expected time complexity is O(C log C), where C is the number of cars.


Constraints:
1 <= Total People <= 10000
1 <= C (number of cars) <= 100
1 <= car capacity <= 100

Time limit: 1 sec
Approaches (1)
Minimum Cars for Group Trip
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Minimum Cars for Group Trip
Full screen
Console