Givenn_items with size Aiand value Vi, and a backpack with size_m. What's the maximum value can you put into the backpack?

Notice

You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.

Have you met this question in a real interview?

Yes

Example

Given 4 items with size[2, 3, 5, 7]and value[1, 5, 2, 4], and a backpack with size10. The maximum value is9.

Challenge

O(n x m) memory is acceptable, can you do it in O(m) memory?

class Solution {

public:

/**

 * @param m: An integer m denotes the size of a backpack

 * @param A & V: Given n items with size A[i] and value V[i]

 * @return: The maximum value

 */

int backPackII(int m, vector<int> A, vector<int> V) {

    // write your code here

    if (A.empty() || V.empty() || m == 0) {

        return 0;

    }

    int n = A.size();

    vector<vector<int>> f(2, vector<int>(m + 1, 0));

    for (int i = 1; i <= n; ++i) {

        for (int j = 1; j <= m; ++j) {

            f[i%2][j] = f[(i - 1)%2][j];

            if (A[i - 1] <= j) {

                f[i%2][j] = max(f[i%2][j], f[(i - 1)%2][j - A[i - 1]] + V[i - 1]);

            }

        }

    }

    return f[n%2][m];

}
};

results matching ""

    No results matching ""