user791134
user791134

Reputation: 203

HackerRank Mark and Toys question in Python

I'm trying to solve this problem: http://www.hackerrank.com/challenges/mark-and-toys For some reason I can't get the correct expected output with my current solution.

Expected output:

He can buy items that cost [1, 5, 10, 12] for 28
The maximum is 4 items

Current output:

He can buy items that cost [1, 5, 10, 12, 111] for 139
The maximum is 5 items

My current solution:

prices = [1, 12, 5, 111, 200, 1000, 10]
k = 50

def maximumToys(prices, k):
    sortedPrices = sorted(prices)
    total = 0
    toys = []
    for i in range(len(sortedPrices)):
        if total <= k:
            total += sortedPrices[i]
            toys.append(sortedPrices[i])
        else:
            break
    print(f"He can buy items that cost {toys} for {total}")
    print(f"The maximum is {len(toys)} items")
    
print(maximumToys(prices, k))

Upvotes: 0

Views: 1307

Answers (3)

Dhruvam Gupta
Dhruvam Gupta

Reputation: 502

BUG in your code has been identified by Krishna Chaurasia.

Another approach could be that subtract the price from k and check if k is still greater than or equal to 0 then increment the count, else break the loop. You don't need to print the complete string message in the function. Just return the value of count from your method. This is what is expected on various coding practice sites.

def maximumToys(prices, k):
prices.sort()
count = 0
for price in prices:
    if k-price >= 0:
        count = count + 1
        k -= price
    else:
        break
return count  

Upvotes: 0

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9572

The problem is with this block of code:

if total <= k:
    total += sortedPrices[i]
    toys.append(sortedPrices[i])

You check the value of total before adding the new element whereas it should be added only if the total doesn't exceed by k after adding the new item.

So, the right code should be:

if total + sortedPrices[i] <= k: # add the item only when we don't exceed by adding it
    total += sortedPrices[i]
    toys.append(sortedPrices[i])

Upvotes: 1

joostblack
joostblack

Reputation: 2525

Your if statement now only determines if you are under the total money and then you add the next item. However you should check if you add the next item, if you are still under the total amount of money that you have. I only changed your if statement:

prices = [1, 12, 5, 111, 200, 1000, 10]
k = 50


def maximumToys(prices, k):
    sortedPrices = sorted(prices)
    total = 0
    toys = []
    for i in range(len(sortedPrices)):
        if total+sortedPrices[i] <= k:
            total += sortedPrices[i]
            toys.append(sortedPrices[i])
        else:
            break
    print(f"He can buy items that cost {toys} for {total}")
    print(f"The maximum is {len(toys)} items")


print(maximumToys(prices, k))

output:

He can buy items that cost [1, 5, 10, 12] for 28
The maximum is 4 items

Upvotes: 1

Related Questions