
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Ice Cream Bars in Python
Suppose we have an array costs with n elements, where costs[i] is the price of the ith ice cream bar in coins. We initially have c number coins to spend, and we want to buy as many ice cream bars as possible. We have to find the maximum number of ice cream bars we can buy with c coins.
So, if the input is like costs = [3,1,4,5,2], c = 10, then the output will be 4 because we can buy ice cream bars at indices 0,1,2,4 for a total price of 3 + 1 + 4 + 2 = 10.
To solve this, we will follow these steps −
sort the list costs
i:= 0
-
while i < size of costs and c >= costs[i], do
c := c - costs[i]
i := i+1
return i
Example
Let us see the following implementation to get better understanding −
def solve(costs, c): costs.sort() i=0 while(i<len(costs) and c >= costs[i]): c = c-costs[i] i=i+1 return i costs = [3,1,4,5,2] c = 10 print(solve(costs, c))
Input
[3,1,4,5,2], 10
Output
4
Advertisements