Answer to Question #309970 in Python for Nikhil

Question #309970

Maximum Number of Books



There are multiple (T) bookstores in the area.Each shopkeeper has a list of B integers that represents the cost of each book.You have different pocket money(P) for each bookstore.Write a program to calculate the maximum number of books you can buy in each store with the corresponding pocket money.



Explanation


Given P = 600 and B = [120, 140, 110, 180, 120, 110] with a pocket money of 600, we can buy the books at index 0,1,2,4,5 , whose sum is 120+140+110+120+110 is equal to P.



Given P = 300 and B = [120 110 1300 130] with a pocket money of 300, we can buy the books at index 0,1 whose sum is 120 + 110 and is less than P.



Given P = 100 and B = [220 1000 500 2000] with pocket money of 100, we can't buy any book. So the output should be Retry.



Sample Input1


3


6 100


20 40 10 80 20 10


4 70


20 10 300 30


4 200


220 1000 500 2000



Sample Output1


5


3





Sample Input2


2


8 250


2070 1350 365 2750 30 20 140 240


4 500


1070 2893 2200 39


Sample Output2


3


1




1
Expert's answer
2022-03-11T14:04:11-0500
t = int(input()) 
result = [0] * t
for i in range(t):
    n, p = map(int, input().split())
    b = sorted(list(map(int, input().split())))
    count = 0
    money = 0
    for cost in b:
        money += cost
        if money <= p:
            count += 1
        else:
            break
    result[i] = count


print(*result, sep='\n')

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS