Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions W2_01knapsack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def knapsack(W, val, wt):
n = len(wt)
dp = [[0 for _ in range(W + 1)] for _ in range(n + 1)]

for i in range(n + 1):
for j in range(W + 1):

# If there are no items or capacity is 0
if i == 0 or j == 0:
dp[i][j] = 0
else:
choose = 0

# Choice 1: choose the current item
if wt[i - 1] <= j:
choose = val[i - 1] + dp[i - 1][j - wt[i - 1]]

# Choice 2: don't choose the current item
dont_choose = dp[i - 1][j]

dp[i][j] = max(choose, dont_choose)

return dp[n][W]


# Time complexity: O(n * W), where n is the number of items and W is the knapsack capacity.
# We fill a DP table of size (n + 1) * (W + 1), and each cell takes O(1) time.

# Space complexity: O(n * W), because we store a 2D DP table with
# (n + 1) rows and (W + 1) columns.
19 changes: 19 additions & 0 deletions W2_two_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
result = []
hashmap = {}

for i in range(len(nums)):
complement = target - nums[i]

if complement not in hashmap:
hashmap[nums[i]] = i
else:
result.append(i)
result.append(hashmap[complement])

return result

# Time complexity: O(N), we visit each element once.
# Space complexity: O(N), if the pair is found at the last index, then the hashmap will have n-1 keys worst case