Skip to content

Instantly share code, notes, and snippets.

@larryfox
Last active August 29, 2015 14:04
Show Gist options
  • Save larryfox/7cb06d542ec62c2afe52 to your computer and use it in GitHub Desktop.
Save larryfox/7cb06d542ec62c2afe52 to your computer and use it in GitHub Desktop.
function knapsack(v, w, capacity)
n = length(v) + 1
capacity += 1
A = zeros(Int, n, capacity)
for j in 1:capacity, i in 2:n
A[i,j] = if w[i-1] < j
max(
A[i-1, j],
A[i-1, j-w[i-1]] + v[i-1]
)
else
A[i-1, j]
end
end
return A[n, capacity], A
end
values = [ 3, 2, 4, 4 ]
weights = [ 4, 3, 2, 3 ]
capacity = 6
total, _ = knapsack(values, weights, capacity)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment