From 7201f9643d3d4326b5278d8791ae0640552a7179 Mon Sep 17 00:00:00 2001 From: takudzwa Date: Tue, 17 Feb 2026 19:46:30 -0500 Subject: [PATCH] [Two sum and knapsack ] --- Problem1.java | 18 ++++++++++++++++++ Problem2.java | 17 +++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/Problem1.java b/Problem1.java index e69de29b..4daf0305 100644 --- a/Problem1.java +++ b/Problem1.java @@ -0,0 +1,18 @@ +public class Problem1 { + + // Time Complexity : O(n) + // Space Complexity : O(n) + // Did this code successfully run on Leetcode : yes + public int[] twoSum(int[] nums, int target) { + Map map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + if (map.containsKey(complement)) { + return new int[] {map.get(complement), i}; + } + map.put(nums[i], i); + } + return new int[] {}; + } +} \ No newline at end of file diff --git a/Problem2.java b/Problem2.java index e69de29b..5a4bcdc6 100644 --- a/Problem2.java +++ b/Problem2.java @@ -0,0 +1,17 @@ +public class Problem2 { + + // Time Complexity : O(n * W_capacity) + // Space Complexity : O(W_capacity) + // Did this code successfully run on Leetcode : yes + public int knapsack(int W, int val[], int wt[]) { + int n = val.length; + int[] dp = new int[W + 1]; + for (int i = 0; i < n; i++) { + for (int j = W; j >= wt[i]; j--) { + dp[j] = Math.max(dp[j], val[i] + dp[j - wt[i]]); + } + } + + return dp[W]; + } +} \ No newline at end of file