From c1282834822f62be577e42d6733f771db1fad079 Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Mon, 16 Feb 2026 20:14:06 -0800 Subject: [PATCH] Competitive Coding 2 --- Knapsack.py | 17 +++++++++++++++++ TwoSum.py | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 Knapsack.py create mode 100644 TwoSum.py diff --git a/Knapsack.py b/Knapsack.py new file mode 100644 index 00000000..44c7fe70 --- /dev/null +++ b/Knapsack.py @@ -0,0 +1,17 @@ +# Time Complexity : O(m * n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : Use 1D array to keep track of max profit for every capacity. + +class Solution: + def knapsack(self, W, val, wt): + n = W + m = len(wt) + dp = [0] * (n+1) + + for i in range(m): + for j in range(n, wt[i] - 1, -1): + dp[j] = max(dp[j], val[i] + dp[j - wt[i]]) + + return dp[n] diff --git a/TwoSum.py b/TwoSum.py new file mode 100644 index 00000000..5dc5fae9 --- /dev/null +++ b/TwoSum.py @@ -0,0 +1,17 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : If complement already in map then return the index else store complement. + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + map = dict() + + for i, num in enumerate(nums): + if target-num in map: + return [i, map[target-num]] + + map[num] = i + + return [-1, -1] \ No newline at end of file