
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 Rocketships Needed for Rescue in Python
Suppose we have a list of numbers called weights this is representing peoples' weights and a value limit determines the weight limit of one rocket ship. Now each rocketship can take at most two people. We have to find the minimum number of rocket ships it would take to rescue everyone to Planet.
So, if the input is like weights = [300, 400, 300], limit = 600, then the output will be 2, as it will take one rocket ship to take the two people whose weights are 300 each, and another to take the person whose weight is 400.
To solve this, we will follow these steps −
sort the list weights
cnt := 0
-
while weights is non-empty, do
x := delete last element from weights
-
if weights is not empty and weights[0] <= limit − x, then
delete first element from weights
cnt := cnt + 1
return cnt
Let us see the following implementation to get better understanding −
Example(Python)
class Solution: def solve(self, weights, limit): weights.sort() cnt = 0 while weights: x = weights.pop() if weights and weights[0] <= limit - x: weights.pop(0) cnt += 1 return cnt ob = Solution() weights = [300, 400, 300] limit = 600 print(ob.solve(weights, limit))
Input
[300, 400, 300], 600
Output
2