Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created May 27, 2022 15:21
Show Gist options
  • Save theabbie/a03b0721cc8542510cf5eff463759321 to your computer and use it in GitHub Desktop.
Save theabbie/a03b0721cc8542510cf5eff463759321 to your computer and use it in GitHub Desktop.
0/1 Knapsack
class Solution:
def knapsack(self, knapsack, target, i, n):
if target < 0:
return -1
if i >= n:
return 0
key = (i, target)
if key in self.cache:
return self.cache[key]
a = 1 + self.knapsack(knapsack, target - knapsack[i], i + 1, n)
b = self.knapsack(knapsack, target, i + 1, n)
res = max(a, b)
self.cache[key] = res
return res
def maximumEvenSplit(self, finalSum: int) -> List[int]:
if finalSum & 1:
return []
knapsack = [el for el in range(2, finalSum + 1, 2)]
n = len(knapsack)
self.cache = {}
self.knapsack(knapsack, finalSum, 0, n)
return knapsack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment