Last active
June 9, 2021 10:44
-
-
Save vitalii-komenda/c996ee2ee4fd6934305dc8677608e401 to your computer and use it in GitHub Desktop.
dp knapsack
This file contains 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
items=[{v: 5, w: 10}, {v: 1, w: 1}, {v: 3, w: 4}] | |
knp = (items, maxWeight)=>{ | |
const dp = []; | |
for(let i=0; i<=items.length; i++) { | |
for(let w=0; w<=maxWeight; w++) { | |
if(!dp[i]) dp[i] = []; | |
dp[i][w] = 0; | |
} | |
} | |
for(let i=1; i<=items.length; i++) { | |
for(let w=1; w<=maxWeight; w++) { | |
let cur = items[i-1]; | |
let notIncludingCur = dp[i-1][w]; | |
let best = dp[i-1][w-cur.w]; | |
dp[i][w] = notIncludingCur; | |
if(w >= cur.w && w-cur.w >= 0 && best + cur.v > dp[i][w]) { | |
dp[i][w] = best + cur.v; | |
} | |
} | |
} | |
return dp[items.length][maxWeight] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment