diff --git a/knapsack.py b/knapsack.py new file mode 100644 index 00000000..803dda8d --- /dev/null +++ b/knapsack.py @@ -0,0 +1,17 @@ + +class Solution: + def finding_weights(self, profit :list[int], weight:list[int], capacity:int)-> int: + n = len(weight) + + dp = [[0 for i in range(capacity + 1)] for j in range(n + 1)] + for i in range(1, n+1): + for j in range(1, capacity+1): + if weight[i-1] > j: + dp[i][j] = dp[i-1][j] + else: + dp[i][j] = max(dp[i-1][j],profit[i-1] + dp[i-1][j-weight[i-1]]) + + return dp[n][capacity] + +solution = Solution() +print(solution.finding_weights([1,2,3],[4,5,1],4)) \ No newline at end of file diff --git a/two_sum.py b/two_sum.py new file mode 100644 index 00000000..2c951485 --- /dev/null +++ b/two_sum.py @@ -0,0 +1,22 @@ +# Two elements sum to target +# Time Complexity: O(n) Space Complexity: O(n) +class Solution: + def twoSum(self,nums:list[int], target: int)-> list[int]: + # defining the empty map + map ={} + + # iterating through the given list + for index, number in enumerate(nums): + # finding the differnce + difference = target - number + # if the difference is present in the map + if difference in map: + # if present then return that index and current index + return [map[difference], index] + # if not present then store the number and corresponing index + else: + map[number] = index + + +solution = Solution() +print(solution.twoSum([2,7,11,15],9)) \ No newline at end of file