diff --git a/Problem1.java b/Problem1.java index e69de29b..ef11ec23 100644 --- a/Problem1.java +++ b/Problem1.java @@ -0,0 +1,19 @@ +//Use a HashMap to store each number’s value -> index as you scan. +// For each nums[i], compute complement = target - nums[i]; if it’s already in the map, return the stored index and i. +// O(n) time with O(n) extra space. + +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int cmp = target - nums[i]; + if (map.containsKey(cmp)) { + return new int[]{map.get(cmp),i}; + } + map.put(nums[i], i); + } + + return new int[]{}; + } +} diff --git a/Problem2.java b/Problem2.java index e69de29b..d34cb934 100644 --- a/Problem2.java +++ b/Problem2.java @@ -0,0 +1,30 @@ +// 0-1 Knapsack via bottom-up DP: dp[i][j] = max value using first i items within capacity j. +// For each item i and capacity j: if wt[i-1] > j -> can't take -> carry dp[i-1][j]; +// else choose max of skipping (dp[i-1][j]) vs taking once (profit[i-1] + dp[i-1][j - wt[i-1]]). +// Time O(m*n) +// Space O(m*n) + +class Solution { + + public static int findMax(int[] weights, int[] profit, int totalCapacity) + { + int n = totalCapacity; + int m = weights.length; + int[][] dp = new int[m+1][n+1]; + + for(int i = 1; i <= m; i++ ) + { + for(int j = 1; j <= n ; j++) + { + if(weights[i-1] > j) + { + dp[i][j] = dp[i-1][j]; + }else { + dp[i][j] = Math.max(dp[i-1][j] , profit[i-1]+dp[i-1][j-weights[i-1]]); + } + } + } + return dp[m][n]; + + } +} \ No newline at end of file