Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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, 30.
Algorithm
To solve this, we will follow these steps −
Initialize count := 0
Sort the list of prices in ascending order
-
For i in range 0 to size of prices, do
-
If prices[i] <= k, then
k := k - prices[i]
count := count + 1
-
Otherwise,
Break from the loop
-
Return count
The key insight is to sort the prices first and buy the cheapest cars to maximize the count.
Example
Let us see the following implementation to get better understanding −
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()
prices = [80, 20, 10, 30, 80]
budget = 85
print(ob.solve(prices, budget))
3
How It Works
The algorithm works as follows ?
Sort prices: [10, 20, 30, 80, 80]
Buy car 1: Price = 10, Budget left = 85 - 10 = 75, Count = 1
Buy car 2: Price = 20, Budget left = 75 - 20 = 55, Count = 2
Buy car 3: Price = 30, Budget left = 55 - 30 = 25, Count = 3
Cannot buy: Price = 80 > 25, so we stop
Alternative Implementation
Here's a more Pythonic version using a simple loop ?
def max_cars(prices, budget):
prices.sort()
count = 0
for price in prices:
if price <= budget:
budget -= price
count += 1
else:
break
return count
# Test the function
prices = [80, 20, 10, 30, 80]
budget = 85
result = max_cars(prices, budget)
print(f"Maximum cars you can buy: {result}")
Maximum cars you can buy: 3
Conclusion
This greedy algorithm maximizes the number of cars by always buying the cheapest available car first. The time complexity is O(n log n) due to sorting, and space complexity is O(1).
---