From 5f8738a04fc80c3b38034294d7df8f39ba8175ef Mon Sep 17 00:00:00 2001 From: rvuyyuru7 Date: Sat, 29 Nov 2025 14:57:03 -0600 Subject: [PATCH] Competitive-Coding-2 complete --- Problem1.java | 27 +++++++++++++++++++++++++++ Problem2.java | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/Problem1.java b/Problem1.java index e69de29b..ec6acc6e 100644 --- a/Problem1.java +++ b/Problem1.java @@ -0,0 +1,27 @@ +// 0-1 Knapsack problem +// Time complexity: O(weights.length * capacity) +// Space complexity: O(capacity) for dp array +public class Problem1 { + public int maxProfit(int[] profits, int[] weights, int capacity) { + int[] dp = new int[capacity + 1]; + for (int row = 1; row < weights.length + 1; row ++) { + // Iterating backwards to avoid using modified dp value. + for (int col = capacity; col >= 1; col --) { + if (col >= weights[row - 1]) { // col is the max capacity + // Consider maximum between previous profit and sum of current weight's profit and maximum profit from the remaining weight. + dp[col] = Math.max(dp[col], profits[row - 1] + (dp[col - weights[row - 1]])); + } + } + } + return dp[capacity]; + } + public static void main(String[] args) { + Problem1 ob = new Problem1(); + int[] profits = new int[] {1, 2, 3}; + int[] weights = new int[] {4, 5, 1}; + int capacity = 4; + System.out.println(ob.maxProfit(profits, weights, capacity)); + capacity = 5; + System.out.println(ob.maxProfit(profits, weights, capacity)); + } +} \ No newline at end of file diff --git a/Problem2.java b/Problem2.java index e69de29b..c97b0e94 100644 --- a/Problem2.java +++ b/Problem2.java @@ -0,0 +1,41 @@ +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +// Approach: HashMap +// Time: O(N) +// Space: O(N) for HashMap +class Solution { + public int[] twoSum(int[] nums, int target) { + Map indexMap = new HashMap<>(); + for (int i = 0; i < nums.length; i ++) { + if (indexMap.containsKey(target - nums[i])) { + return new int[] {indexMap.get(target - nums[i]), i}; + } + indexMap.put(nums[i], i); + } + throw new IllegalArgumentException("No solution"); + } + + public static void main(String[] args) { + Solution ob = new Solution(); + + int[] nums1 = {2,7,11,15}; + System.out.println(Arrays.toString(ob.twoSum(nums1, 9))); // returns [0, 1] + + int[] nums2 = {3,2,4}; + System.out.println(Arrays.toString(ob.twoSum(nums2, 6))); // returns [1, 2] + + int[] nums3 = {3,3}; + System.out.println(Arrays.toString(ob.twoSum(nums3, 6))); // returns [0, 1] + + int[] nums4 = {3}; + System.out.println(Arrays.toString(ob.twoSum(nums4, 3))); // throws exception + + int[] nums5 = {}; + System.out.println(Arrays.toString(ob.twoSum(nums5, 0))); // throws exception + + int[] nums6 = {2, 3}; + System.out.println(Arrays.toString(ob.twoSum(nums6, 4))); // throws exception + } +} \ No newline at end of file