From 53348f1437b6e0a9ca5f4fba2e329c32cc063983 Mon Sep 17 00:00:00 2001 From: Kartavya Bhatt Date: Sat, 27 Jun 2026 20:03:43 -0400 Subject: [PATCH] CC-2 complete --- Problem1.py | 18 ++++++++++++++++++ Problem2.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 Problem1.py create mode 100644 Problem2.py diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..ab068435 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,18 @@ +''' +The solution is to find a matching number given to the current number. +Matching number for a current number is the one that produces the sum = target. + +We keep a hashmap of the numbers visited before along with their index. +For the current number if we find the target - current number then we return +indexes of the numbers. + +Time complexity: O(n) +Space complexity: O(n) +''' +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + hMap = {} + for idx, i in enumerate(nums): + if target - i in hMap: + return [hMap[target-i], idx] + hMap[i] = idx \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..23e18693 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,38 @@ +''' +Brute force is to traverse a tree of the choice being choose or not choose +a given item until the bag is full or items can no longer be fit. +Time complexity: O(2^n) +Space complexity: O(n) + +We can use the dp to optimize the repeated subproblems. +Using the given items calculate the maximum profit with capacity k. +Start the k from 0 to W. +Keep adding items until the entire grid is filled in the dp. + +Choosing an item (i) means we are choosing max profit from the items before i +and capacity of w - w[i]. Then we add i to get final capacity of w and maximum +profit by adding i. + +Hence the formula: +dp[j] = max(prev[j], valMap[w] + prev[j-w]) +Time complexity = O(W * n) +Space complexity = O(W) +''' +class Solution: + def knapsack(self, W, val, wt): + # code here + valMap = {} + for i in range(len(wt)): + valMap[wt[i]] = val[i] + + prev = [0 for _ in range(W+1)] + dp = [0 for _ in range(W+1)] + sortedWeights = sorted(wt) + + for w in sortedWeights: + for j in range(w, W+1): + dp[j] = max(prev[j], valMap[w] + prev[j-w]) + + prev = dp + + return dp[-1] \ No newline at end of file