Created
May 27, 2022 15:21
-
-
Save theabbie/a03b0721cc8542510cf5eff463759321 to your computer and use it in GitHub Desktop.
0/1 Knapsack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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