Find the maximum distance covered using n bikes in Python


Suppose there are n bikes and each can cover 100 km when they are fully fueled. We have to find the maximum amount of distance we can go using these n bikes. Here we can assume that all bikes are similar and a bike consumes 1 litre of fuel to cover 1 km distance. So, if n bikes start from same point and run parallel, we can go only 100 km, in this case our target is to cover maximum distance, with minimum fuel. And minimum wastage of fuel means minimum number of bikes used. If the bikes run serially, then helps to cover more distance. So, we transfer some amount of fuel from last bike to another bike and don’t run the last bike after certain point. But now the problem is what distance the fuel transfer has to be performed such that the maximum distance is covered and fuel tank of rest of the bikes do not overflow.

So, if the input is like n = 3 and fuel = 100, then the output will be 183.33

To solve this, we will follow these steps −

  • covered_diatance := 0

  • while n > 0 is non-zero, do

    • covered_diatance := covered_diatance + (fuel / n)

    • n := n - 1

  • return covered_diatance

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def maximum_distance(n, fuel):
   covered_diatance = 0
   while (n > 0):
      covered_diatance = covered_diatance + (fuel / n)
      n = n - 1
   return covered_diatance
n = 3
fuel = 100
print(maximum_distance(n, fuel))

Input

3, 100

Output

183.33333333333334

Updated on: 20-Aug-2020

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements