BiruLyu
9/21/2017 - 2:06 AM

0-1 Knapsack Problem.java


public class KnapsackProblem {
	public static int maximumValue(int W, int[] w, int[] b) {// W -> capacity, w -> weight, b -> benefit
		int n = w.length;
		// dp[i][j] defines the optimal solution with first i items and total capacity j
		int[][] dp = new int[n + 1][W + 1];
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= W; j++) {
				if (w[i - 1] <= j) {
					dp[i][j] = Math.max(dp[i - 1][j], b[i - 1] + dp[i - 1][j - w[i - 1]]);
				} else {
					dp[i][j] = dp[i - 1][j];
				}
			}
		}
		return dp[n][W];
	}
	public static void main(String[] args) {
		//Testcase01: 9
		int W1 = 7;
		int[] w1 = {1,3,4,5}, b1 = {1,4,5,7};
		System.out.println("Tesecase01: " + maximumValue(W1, w1, b1));
		
		//Testcase02: 7
		int W2 = 5;
		int[] w2 = {2,3,4,5}, b2 = {3,4,5,6};
		System.out.println("Tesecase02: " + maximumValue(W2, w2, b2));
		
	}

}