Backpack
Written on October 21, 2015
Tweet
Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
public class Solution {
public int backPack(int m, int[] A) {
// write your code here
if (A == null || A.length == 0) return 0;
int[] size = new int[m + 1];
//previous i items fill size j
for (int i = 1; i <= A.length; i++) {
for (int j = m; j >= 0; j--) {
if (j >= A[i-1]) {
size[j] = Math.max(size[j], size[j-A[i-1]] + A[i-1]);
}
}
}
return size[m];
}
}
public class 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) {
// write your code here
if (A == null || A.length == 0) return 0;
int[][] size = new int[A.length + 1][m + 1];
//previous i items fill size j
for (int i = 1; i <= A.length; i++) {
for (int j = 1; j <= m; j++) {
if (j >= A[i-1]) {
size[i][j] = Math.max(size[i-1][j], size[i-1][j-A[i-1]] + A[i-1]);
} else {
size[i][j] = size[i-1][j];
}
}
}
return size[A.length][m];
}
}