Skip to content

Instantly share code, notes, and snippets.

@dongr0510
Created September 10, 2020 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dongr0510/998cd84953551e7cb234d0ccca4b225c to your computer and use it in GitHub Desktop.
Save dongr0510/998cd84953551e7cb234d0ccca4b225c to your computer and use it in GitHub Desktop.
def solve_knapsack(profits, weights, capacity):
return solve_knapsack_recursive(profits, weights, capacity, 0)
def solve_knapsack_recursive(profits, weights, capacity, currentIndex):
n = len(profits)
# base checks
if capacity <= 0 or n == 0 or len(weights) != n or currentIndex >= n:
return 0
# recursive call after choosing the items at the currentIndex, note that we recursive call on all
# items as we did not increment currentIndex
profit1 = 0
if weights[currentIndex] <= capacity:
profit1 = profits[currentIndex] + solve_knapsack_recursive(
profits, weights, capacity - weights[currentIndex], currentIndex)
# recursive call after excluding the element at the currentIndex
profit2 = solve_knapsack_recursive(
profits, weights, capacity, currentIndex + 1)
return max(profit1, profit2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment