logo
Problems

Backpack

Problem

Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?

Example

If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select [2, 3, 5], so that the max size we can fill this backpack is 10. If the backpack size is 12. we can select [2, 3, 7] so that we can fulfill the backpack.

You function should return the max size we can fill in the given backpack.

Note

You can not divide any item into small pieces.

Challenge

O(nm) time and O(m) memory.

O(nm) memory is also acceptable if you do not know how to optimize memory.

Solution

A typical dynamic programming problem. You do not need to store the whole matrix, we just need 2 rows, so we can bring down space complexity to O(m).

Online Judge