Buying Cars in Python


Suppose we have a list of prices of cars for sale, and we also have a budget k, we have to find the maximum number of cars we can buy.

So, if the input is like [80, 20, 10, 30, 80], k = 85, then the output will be 3 as we can buy three cars with prices 20, 10, 40

To solve this, we will follow these steps −

  • count := 0

  • sort the list prices

  • for i in range 0 to size of prices, do

    • if prices[i] <=k, then

      • k := k-prices[i]

      • count := count + 1

    • otherwise,

      • come out from the loop

  • return count

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, prices, k):
      count =0
      prices.sort()
      for i in range(len(prices)):
         if(prices[i]<=k):
            k = k-prices[i]
            count += 1
         else:
            break
      return count
ob = Solution()
p = [80, 20, 10, 30, 80]
print(ob.solve(p, 85))

Input

[80, 20, 10, 30, 80], 85

Output

3

Updated on: 02-Sep-2020

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements