public class Knapsack_unbounded_dp { static int M[]; // M[j] = Max value achieved using knapsack cap j /* ============================================================= make_M(v, w, M): make the M[] array v[] = value of each type of item w[] = weight of each type of item M[j] = Max value achieved using knapsack cap j Return: the value M[C] (which is the max value you can pack in a knapsack of capacity C ============================================================= */ static int make_M(int[] v, int[] w, int[] M) { int sol = 0, my_sol; int j, k, max; /* --------------------------- Base case --------------------------- */ M[0] = 0; // 0 value for knapsack of capacity 0 /* --------------------------------------------------- The other cases (starting from 1 to M.length - 1) --------------------------------------------------- */ for ( j = 1; j < M.length; j++ ) { if ( M.length < 20 ) System.out.println("\nComputing M[" + j + "]"); /* ========================================================== When for any value j, we have the solutions for: M[0] M[1] ... M[j-1] M[x] = Max value achieved using knapsack cap x We can compute M[j] as: M[j] = max( M[j - v[k]] + w[k] ) k = 0, 1, 2, ..., i-1 ========================================================== */ max = 0; // No items in knapsack for ( k = 0; k < v.length; k++ ) { /* -------------------------------------------- Check if we can use the k-th typed item -------------------------------------------- */ if ( w[k] <= j ) { /* ------------------------ Divide step ------------------------ */ sol = M[j - w[k]]; // Find best solution with item k // packed as last item /* --------------------------------------- Conquer: solve original problem using solution from smaller problems --------------------------------------- */ my_sol = sol + v[k]; // See class notes if ( M.length < 20 ) System.out.println(" " + my_sol ); /* --------------------------------------- Determine the best (last) item to use --------------------------------------- */ if ( my_sol > max ) max = my_sol; // A better solution found } } M[j] = max; if ( M.length < 20 ) System.out.println("=====> M[" + j + "] = " + M[j]); } return( M[M.length-1] ); } public static void main(String[] args) { int[] v = {1, 2, 3, 5, 6, 8}; int[] w = {2, 3, 5, 8, 9, 13}; int C, r; C = 18; // Around 53 it starts to slow... M = new int[ C + 1]; r = make_M(v, w, M); /* for (i = 0; i <= C; i ++) System.out.println("M[" + i + "] = " + M[i]); */ System.out.println("Max value for knapsack of cap " + C + " = " + r); } }