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 have4
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 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:
0 - 1 backpack problem
Space-optimized Solution:
dp[j] = for size j, there is a solution for current A[0, ... i] items
dp[0] = True
in reverse order: dp[j] |= dp[j - A[i]] # we can insert item A[i] into j
solution : max i such that dp[i] == 1
Non-optimized Solution:
dp[i][j]: for (i - 1) th item i, whether size j contain full bag (0th is for initial state)
dp[.][0] = True
in left-right order: dp[i][j] = dp[i - 1][j - A[i - 1]] for j >= A[i - 1]
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?