- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements