Skip to content

Instantly share code, notes, and snippets.

@me-shaon
Created November 11, 2023 13:35
Show Gist options
  • Save me-shaon/7c1eff004d1d227e6d7cdd35e213dedf to your computer and use it in GitHub Desktop.
Save me-shaon/7c1eff004d1d227e6d7cdd35e213dedf to your computer and use it in GitHub Desktop.
0/1 Knapsack (Javascript)
module.exports = {
//param A : array of integers
//param B : array of integers
//param C : integer
//return an integer
solve : function(A, B, C){
let n = A.length;
let maxValue = Array.from({length: C + 1}).fill(0);
for (let i=1; i<=n; i++) {
for (let j=C; j>=B[i-1]; j--) {
maxValue[j] = Math.max(maxValue[j - B[i-1]] + A[i-1], maxValue[j]);
}
}
return maxValue[C];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment