FunctionRacerProblemsRace

Lighten the Bag

EasyGreedyPython, JavaScript, TypeScript, Java, C++

weights lists the weights of the items packed in a bag, and the bag may weigh at most limit in total. Remove the fewest items so that the total weight of what remains is at most limit. Return the number of items removed, which is 0 if the bag is already light enough (including when weights is empty).

Example 1

weights [4,8,1,5]
limit 10
returns 1

The bag weighs 18. Removing the 8 leaves 10, which is within the limit, and no single lighter item would do.

Example 2

weights [3,3,3]
limit 5
returns 2

The bag weighs 9. After one removal it weighs 6, still over 5, so a second item must go.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Greedy problems