diff --git a/Knapsack01.java b/Knapsack01.java new file mode 100644 index 00000000..3c1ed2c2 --- /dev/null +++ b/Knapsack01.java @@ -0,0 +1,28 @@ +// Idea is to use pick and no pick elements to fill the knapsack +// Use bottom up - DP array to store sub problem results and use them to solve larger problems +// Time Complexity: O(n) +// Space Complexity: O(n) +public class Knapsack01{ + + public int knapsack(int W, int[] val, int[] wt,int index) { + 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 there is no item or the knapsack's capacity is 0 + if (i == 0 || j == 0) + dp[i][j] = 0; + else { + int pick = 0; + // Pick ith item if it does not exceed the capacity of knapsack + if (wt[i - 1] <= j) + pick = val[i - 1] + dp[i - 1][j - wt[i - 1]]; + int notPick = dp[i - 1][j]; + dp[i][j] = Math.max(pick, notPick); + } + } + } + return dp[n][W]; + } +} \ No newline at end of file diff --git a/Problem1.java b/Problem1.java deleted file mode 100644 index e69de29b..00000000 diff --git a/Problem2.java b/Problem2.java deleted file mode 100644 index e69de29b..00000000 diff --git a/TwoSumProblem.java b/TwoSumProblem.java new file mode 100644 index 00000000..c82f6a8d --- /dev/null +++ b/TwoSumProblem.java @@ -0,0 +1,24 @@ +import java.util.HashMap; + +//Idea is to use Hashmap to store the value and index. +//While inserting into the hashmap we simultaneously check for the compliment value (target-current value) +// Time Complexity: O(n) +// Space Complexity: O(n) +public class TwoSumProblem{ + + public int[] twoSum(int[] nums, int target) { + HashMap hm = new HashMap(); + for(int i=0;i