public class TabularKnapsack { public static void main(String[] args ) { int[] p = { 100, 50, 30, 15, 7, 3 }; int[] w = { 90, 60, 21, 8, 8, 5 }; int M = 164; System.out.println( solve( p, w, M ) ); } public static int solve( int[] p, int[] w, int M ) { int[] knapsack = new int[ M+1 ]; int[] optimum = new int[ M+1 ]; int n = p.length; for ( int j = 0; j <= M; ++j ) { knapsack[ j ] = 0; optimum[ j ] = 0; } for ( int i = 0; i < n; ++i ) { for ( int j = (M - w[ i ]); 0 <= j; --j ) { int iprofit = p[i]; int iweight = w[i]; if ( optimum[ j ] + iprofit > optimum[ j + iweight ] ) { optimum[ j + iweight ] = optimum [ j ] + iprofit; knapsack[ j + iweight ] = i; } } } return optimum[M]; } }