# input: v[0..N) and w[0..N) arrays of natural numbers, N>=0, and C>=0## output: Maximum retribution by choosing elements with individual# retribution and weight in v[0..N) and w[0..N), respectively,# to carry in a knapsack with weight capacity C## O(NC) time and O(C) space solutiondefks_tab_opt(v,w,C):N=len(v)tab=[0forcinrange(C+1)]n,c=1,Cwhilen!=N+1:ifc==-1:n,c=n+1,Celse:ifw[n-1]<=c:tab[c]=max(tab[c],v[n-1]+tab[c-w[n-1]])c-=1returntab[C]
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.