GRDY-P1

How much of each item

Practice 1 of 6Greedy algorithms10 tests

The problem

A bag holds capacity kg. Each item is a pair (weight, value), and any part of an item may be taken: x kg of an item is worth x * value / weight. Lesson 1 worked out the largest value. Here, return the plan itself: a list with one number per item, in the order the items are given, saying how many kilograms of that item go in the bag.

how_much(8, [(5, 10), (4, 7), (3, 3), (2, 5)])
# [5, 1, 0, 2]: all of the first and last items,
# 1 kg of the second; worth 10 + 1.75 + 5 = 16.75

Each amount must be between 0 and its item’s weight, and the amounts together must fit in the bag. Any plan with the largest value passes: the tests report the value of your plan (compared to 9 significant figures), or what is wrong with it. Every weight is a whole number of at least 1, every value a whole number of at least 0, and capacity is at least 0.

Limits

  • Up to 200,000 items. Aim for O(n log n).

Builds on GRDY-1 The greedy choice.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

10 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Everything fitsNot run
3Cut the only itemNot run
4An empty bagNot run
5No itemsNot run
6Valuable but heavyNot run
7Light but cheapNot run
8Amounts in the order givenNot run
9Items worth nothingNot run
10200,000 itemsNot run