diff --git a/knapsackUnbounded.class b/knapsackUnbounded.class new file mode 100644 index 0000000..c50c6d0 Binary files /dev/null and b/knapsackUnbounded.class differ diff --git a/knapsackUnbounded.java b/knapsackUnbounded.java new file mode 100644 index 0000000..dff1e73 --- /dev/null +++ b/knapsackUnbounded.java @@ -0,0 +1,36 @@ +import java.util.*; +class knapsackUnbounded{ + + static int solve(int[] wt,int[] val,int w){ + int n=wt.length; + int[][] dp=new int[n+1][w+1]; + for(int i=0;i<=n;i++){ + for(int j=0;j<=w;j++){ + if(i==0 || j==0){ + dp[i][j]=0; + } + else if(wt[i-1]<=j){ + dp[i][j]=Math.max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]); + } + else{ + dp[i][j]=dp[i-1][j]; + } + } + } + return dp[n][w]; + } + + public static void main(String[] args){ + int[] wt={1,2,3,4,5,6,7}; + // given weight array to be filled in knapsack + + int[] val={11,9,13,18,16,18,22}; + // given a value array ,to the corresponding ith weight + // int weight array + + int w=18; + //weight capacity of knapsack + + System.out.println(solve(wt,val,w)); + } +} diff --git a/knapsack_01.class b/knapsack_01.class new file mode 100644 index 0000000..d06ff59 Binary files /dev/null and b/knapsack_01.class differ diff --git a/knapsack_01.java b/knapsack_01.java new file mode 100644 index 0000000..092e59d --- /dev/null +++ b/knapsack_01.java @@ -0,0 +1,35 @@ +import java.util.*; +class knapsack_01{ + + static int solve(int[] wt,int[] val,int w){ + int n=wt.length; + int[][] dp=new int[n+1][w+1]; + for(int i=0;i<=n;i++){ + for(int j=0;j<=w;j++){ + if(i==0 || j==0){ + dp[i][j]=0; + } + else if(wt[i-1]<=j){ + dp[i][j]=Math.max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j]); + } + else{ + dp[i][j]=dp[i-1][j]; + } + } + } + return dp[n][w]; + } + public static void main(String[] args){ + int[] wt={1,2,3,4,5,6,7}; + // given a weight array + + int[] val={12,21,13,15,19,23,25}; + // given a value array,containing values of ith weight + // of weight array + + int w=15; + // given the capacity of knapsack + + System.out.println(solve(wt,val,w)); + } +}