Program to 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)

 Live Demo

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

Updated on: 21-Oct-2020

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements