Program to 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

Updated on: 07-Oct-2021

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements