Skip to the content

The game shop

Problem

"Whatever that buys you," says the village shopkeeper, and your character empties the pouch onto the counter. You want to walk out of the shop with as many items as possible, no matter which ones.

Write a function that takes prices, a list of positive integers (it may be empty or have repeated prices; each price is a separate item), and coins, an integer from 0 up. Return an integer: the most items you can buy, each one only once, without spending more coins than you carry. Spending exactly all of them is fine.

With prices 12, 5, 8, 20 and 3 and 20 coins: you buy the 3, the 5 and the 8, and spend 16. Any fourth item puts you over. The answer is 3.

With no items, or no coins, you buy 0.

Examples

  • The example

    [12, 5, 8, 20, 3], 20 → 3

  • Spending exactly everything

    [4, 6, 10], 10 → 2

  • Repeated prices

    [7, 7, 7], 20 → 2

  • Enough for everything

    [2, 3, 1], 100 → 3

  • No coins

    [1, 2], 0 → 0

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def shopping(prices, coins):
    pass

JavaScript

function shopping(prices, coins) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →