import java.util.Scanner; public class Knapsack1_dp { /* =========================================================== M(n, W) = max value achieved by knapsack with capacity W filled with items 0, 1, ..., n-1 =========================================================== */ static int M(int[] v, int[] w, int n, int W) { int sol1, sol2, mySol1, mySol2; int k, C; int[][] M; M = new int[n+1][W+1]; // Data structure /* --------------------------- Base cases --------------------------- */ for ( int j = 0; j <= W; j++ ) M[0][j] = 0; // (k=0) No more items to pick from for ( int i = 0; i <= n; i++ ) M[i][0] = 0; // (C=0) No more space for ( k = 1; k <= n; k++ ) { for ( C = 1; C <= W; C++ ) { /* -------------------------------------------- Check if we can use the n-th typed item -------------------------------------------- */ if ( w[k-1] > C ) // Item k-1 does not fit... { M[k][C] = M[k-1][C]; // We must leave item k-1 out } else { /* ==================================== Solve smaller problems ==================================== */ sol1 = M[k-1][C]; // Try leaving item k out sol2 = M[k-1][C-w[k-1]]; // Try packing item k /* ========================================================== Use solution of smaller problems to solve my problem ========================================================== */ mySol1 = sol1; // I did not pack item k-1, so no added value mySol2 = sol2 + v[k-1]; // I packed item k-1, so add v[k-1] ! if ( mySol1 > mySol2 ) M[k][C] = mySol1; else M[k][C] = mySol2; } } } return(M[n][W]); // Max value to pack n item in knapsack cap W } public static void main(String[] args) { int[] v, w; int n; int C, r; Scanner in = new Scanner( System.in ); System.out.print("Number of items: "); n = in.nextInt(); System.out.println(); v = new int[n]; w = new int[n]; for ( int i = 0; i < n; i++ ) { System.out.print("Weight of item " + i + ": "); w[i] = in.nextInt(); System.out.print("Value of item " + i + ": "); v[i] = in.nextInt(); System.out.println(); } System.out.print("Capacity of knapsack: "); C = in.nextInt(); r = M(v, w, w.length, C); System.out.println("\nMax value packed in backpack = " + r); } }