Backpack I

Description

Given n _items with size _Ai, an integer _m _denotes the size of a backpack. How full you can fill this backpack?

You can not divide any item into small pieces.

Have you met this question in a real interview?

Yes

Example

If we have4items 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 is10. If the backpack size is12. 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.

Challenge

O(n x m) time and O(m) memory.

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

Thoughts:

  1. 0 - 1 backpack problem

  2. Space-optimized Solution:

    1. dp[j] = for size j, there is a solution for current A[0, ... i] items

    2. dp[0] = True

    3. in reverse order: dp[j] |= dp[j - A[i]] # we can insert item A[i] into j

    4. solution : max i such that dp[i] == 1

  3. Non-optimized Solution:

    1. dp[i][j]: for (i - 1) th item i, whether size j contain full bag (0th is for initial state)

    2. dp[.][0] = True

    3. in left-right order: dp[i][j] = dp[i - 1][j - A[i - 1]] for j >= A[i - 1]

  4. real value Solution

Code T: 2614 ms O(m * n); S: O(m)

Code T: O(m * n) 6288 ms; S: O(m * n)

Code T: O(m * n) 2397 ms; S: O(m)

Last updated

Was this helpful?