diff --git a/Knapsack.java b/Knapsack.java new file mode 100644 index 00000000..4d617864 --- /dev/null +++ b/Knapsack.java @@ -0,0 +1,19 @@ + // TimeComplexity: O(n x W) + // SpaceComplexity: O(W) + + static int knapsack(int W, int[] val, int[] wt) { + + // Initializing dp array + int[] dp = new int[W + 1]; + + // Taking first i elements + for (int i = 1; i <= wt.length; i++) { + + // Starting from back, so that we also have data of + // previous computation of i-1 items + for (int j = W; j >= wt[i - 1]; j--) { + dp[j] = Math.max(dp[j], dp[j - wt[i - 1]] + val[i - 1]); + } + } + return dp[W]; + } diff --git a/Problem1.cpp b/Problem1.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/Problem1.java b/Problem1.java deleted file mode 100644 index e69de29b..00000000 diff --git a/Problem2.cpp b/Problem2.cpp 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/TwoSum.java b/TwoSum.java new file mode 100644 index 00000000..dc1ac9d5 --- /dev/null +++ b/TwoSum.java @@ -0,0 +1,18 @@ +// TimeComplexity: O(n) +// SpaceComplexity: O(n) +// Explanation: I am iterating through the array and storing the elemnet in the hashmap with its index if the compliment is not found. If the compliment is found I am returning the compliment index and the current index. + +class Solution { + public int[] twoSum(int[] nums, int target) { + int n = nums.length; + HashMap map = new HashMap<>(); + for(int i=0; i