progress

~/problems / 2-D dynamic programming / Knapsack and coin change

Most pages within a budget

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

A shop has n books; book i costs prices[i] and has pages[i] pages. Buy each book at most once, spending at most budget, to get the most pages.

Implement book_shop(prices: list[int], pages: list[int], budget: int) -> int.

book_shop([4, 8, 5, 3], [5, 12, 8, 1], 10)  # 13   books 0 and 2: price 9, pages 5 + 8
book_shop([7], [100], 6)                    # 0    can't afford anything

Up to 100 books, budget <= 5000, prices and pages up to 1000.

⭐ Bonus: a speed test with 100 books and a 5,000 budget earns a star in O(n × budget). Trying all 2^n subsets is exponential.

Show hint

track the most pages for each possible total spend, adding one book at a time, so no book is counted twice.

Topic: Knapsack and coin change. 0/1 vs unbounded; loop order decides combinations vs permutations.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc