diff --git a/Enhancement of the knapsack algorithm #9266 b/Enhancement of the knapsack algorithm #9266 new file mode 100644 index 000000000000..ce5593ddce49 --- /dev/null +++ b/Enhancement of the knapsack algorithm #9266 @@ -0,0 +1,70 @@ +The following is a Python implementation of the 0-1 knapsack problem with memorization: + +def knapsack_memorization(weights, values, capacity): + """Solves the 0-1 knapsack problem using memorization. + + Args: + weights: A list of weights of the items. + values: A list of values of the items. + capacity: The capacity of the knapsack. + + Returns: + The maximum value of the items that can be placed in the knapsack. + """ + + memo = {} + + def knapsack_helper(i, capacity): + if i == 0 or capacity == 0: + return 0 + + key = (i, capacity) + if key in memo: + return memo[key] + + if weights[i - 1] > capacity: + max_value = knapsack_helper(i - 1, capacity) + else: + max_value = max(knapsack_helper(i - 1, capacity), + values[i - 1] + knapsack_helper(i - 1, capacity - weights[i - 1])) + + memo[key] = max_value + return max_value + + return knapsack_helper(len(weights), capacity) + + + +The following is a Python implementation of the 0-N knapsack problem: + +def knapsack_0_n(weights, values, capacity): + """Solves the 0-N knapsack problem. + + Args: + weights: A list of weights of the items. + values: A list of values of the items. + capacity: The capacity of the knapsack. + + Returns: + The maximum value of the items that can be placed in the knapsack. + """ + + memo = {} + + def knapsack_helper(i, capacity): + if i == 0 or capacity == 0: + return 0 + + key = (i, capacity) + if key in memo: + return memo[key] + + max_value = 0 + for j in range(1, capacity // weights[i - 1] + 1): + max_value = max(max_value, values[i - 1] * j + knapsack_helper(i - 1, capacity - weights[i - 1] * j)) + + memo[key] = max_value + return max_value + + return knapsack_helper(len(weights), capacity) +