Backpack I

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

time and memory.

memory is also acceptable if you do not know how to optimize memory.

Think

  • Setup 2-D memorized array with length is memo[items.length][bag size]
  • memo[i][S] means what is the max size we can fill in when get first i items.
  • Then we should check from zero to M size when got ith items and evaluate the max size when taken or not taken current ith item.

Solution

    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @return: The maximum size
     */
    public int backPack(int M, int[] A) {
        int[][] bp = new int[N + 1][M + 1];

        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j <= M; j++) {
                if (A[i] > j) {
                    bp[i + 1][j] = bp[i][j];
                } else {
                    bp[i + 1][j] = Math.max(bp[i][j], bp[i][j - A[i]] + A[i]); // add the A[i]- size itself
                }
            }
        }
        return bp[N][M];
    }

results matching ""

    No results matching ""