File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ public class KnapsackProblem {
2+ public static void main (String [] args ) {
3+ int [] weights = {1 , 2 , 3 };
4+ int [] values = {10 , 15 , 40 };
5+ int capacity = 6 ;
6+ System .out .println ("Maximum value in Knapsack = " + knapsack (weights , values , capacity ));
7+ }
8+
9+ public static int knapsack (int [] weights , int [] values , int capacity ) {
10+ int n = weights .length ;
11+ int [][] dp = new int [n + 1 ][capacity + 1 ];
12+
13+ for (int i = 0 ; i <= n ; i ++) {
14+ for (int w = 0 ; w <= capacity ; w ++) {
15+ if (i == 0 || w == 0 ) {
16+ dp [i ][w ] = 0 ; // Base case: no items or no capacity
17+ } else if (weights [i - 1 ] <= w ) {
18+ dp [i ][w ] = Math .max (dp [i - 1 ][w ], // Exclude the item
19+ dp [i - 1 ][w - weights [i - 1 ]] + values [i - 1 ]); // Include the item
20+ } else {
21+ dp [i ][w ] = dp [i - 1 ][w ]; // Exclude the item
22+ }
23+ }
24+ }
25+ return dp [n ][capacity ];
26+ }
27+ }
You can’t perform that action at this time.
0 commit comments