diff --git a/0-1Knapsack.java b/0-1Knapsack.java new file mode 100644 index 00000000..ad59d634 --- /dev/null +++ b/0-1Knapsack.java @@ -0,0 +1,34 @@ +// Time Complexity : O(m * n) +// Space Complexity : O(n) +// Any problem you faced while coding this : no + +// Your code here along with comments explaining your approach +/* +This problem cant be solved in greedy,so while solving recursively, we see a lot of repetitive subproblems +to be solved.This can be done through DP. We take a DP array to respectively handle choose and no choose +cases of weights and match with capacity, thereby compute the max profit at every step + */ +class Solution { + + public static int findMax(int[] weights, int[] profit, int totalCapacity) { + int m = weights.length; + int n = totalCapacity; + + int[] dp = new int[n + 1]; + + for(int i = 0 ; i < m ; i++) { + for(int j = n ; j >= weights[i] ; j--) { + dp[j] = Math.max(dp[j], profit[i] + dp[j - weights[i]]); + } + } + return dp[n]; + } + + public static void main(String args[]) { + int[] items = {10, 20, 30, 40}; + int[] profit = {130, 110, 170, 190}; + int capacity = 50; + + System.out.println(findMax(items, profit, capacity)); + } +} 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/TwoSum.java b/TwoSum.java new file mode 100644 index 00000000..b4b238d9 --- /dev/null +++ b/TwoSum.java @@ -0,0 +1,25 @@ +// Time Complexity : O(n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + + +// Your code here along with comments explaining your approach +/* +I would take a map of integers and iterate the input array. During iteration, if complement/difference of +the target and incoming array element value already exists in the map, it means, we already recorded the +associated value to make the sum inside the map.So,we fetch and return that value(index) and +index of i. If not, record the first occurence of that nums[i] and its index. + */ +class Solution { + public int[] twoSum(int[] nums, int target) { + Map sumMap = new HashMap(); + for(int i = 0; i < nums.length; i++) { + int diff = target - nums[i]; + if(sumMap.containsKey(diff)) + return new int[]{i,sumMap.get(diff)}; + sumMap.put(nums[i], i); + } + return new int[]{}; + } +} \ No newline at end of file