public class Knapsack_unbounded { /* ======================================================== M(j) = max value achieved by knapsack with capacity j ======================================================== */ static int M(int[] v, int[] w, int j) { int sol, my_sol; int k, max; /* --------------------------- Base cases --------------------------- */ if ( j == 0 ) { return(0); } max = 0; // No items in knapsack for ( k = 0; k < v.length; k++ ) { /* -------------------------------------------- Check if we can use the k-th type item -------------------------------------------- */ if ( w[k] <= j ) { /* ------------------------ Divide step ------------------------ */ sol = M(v, w, j - w[k]); // Try item of type k // with weight w[k] /* --------------------------------------- Conquer: solve original problem using solution from smaller problems --------------------------------------- */ my_sol = sol + v[k]; // See class notes /* --------------------------------------- Determine the best (last) item to use --------------------------------------- */ if ( my_sol > max ) max = my_sol; // A better solution found } } return(max); // Return the overal best solution } 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... r = M(v, w, C); System.out.println("Max value packed in backpack of capacity " + C + " = " + r); } }