-
Notifications
You must be signed in to change notification settings - Fork 0
/
knapsack.js
55 lines (48 loc) · 1.56 KB
/
knapsack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
let weights = [2, 3, 1, 4 ];
let profits = [4, 5, 3, 7];
let capacity = 5;
// 0 1 2 3 4 5
//0 0 0 0 0 0 0
//4 0 0 1
//4,5
//4,5,3,7
///bound knapsack with out dp
function maxKnapsack(weights, profits, capacity, currentIndex){
let profit1 = -1
if (profits.length <=currentIndex || capacity < 0 ){
return 0;
}
if (weights[currentIndex] <= capacity){
profit1 = profits[currentIndex] + maxKnapsack(weights, profits, capacity - weights[currentIndex], currentIndex + 1);
}
profit2 = maxKnapsack(weights, profits,capacity,currentIndex + 1 )
return Math.max(profit1, profit2)
}
console.log(maxKnapsack(weights,profits,capacity,0))
//knapsack with dynamic programming
let weights = [2, 3, 1, 4 ];
let profits = [4, 5, 3, 7];
let capacity = 5;
// 0 1 2 3 4 5
//0 0 0 0 0 0 0
//4 0 0 1
//4,5
//4,5,3,7
let dp = []
function maxKnapsack(weights, profits, capacity, currentIndex){
let profit1 = -1
if (profits.length <=currentIndex || capacity < 0 ){
return 0;
}
dp[currentIndex] = dp[currentIndex] || [];
if (dp[currentIndex][capacity]!= undefined){
return dp[currentIndex][capacity];
}
if (weights[currentIndex] <= capacity){
profit1 = profits[currentIndex] + maxKnapsack(weights, profits, capacity - weights[currentIndex], currentIndex + 1);
}
profit2 = maxKnapsack(weights, profits,capacity,currentIndex + 1 )
dp[currentIndex][capacity]= Math.max(profit1, profit2);
return dp[currentIndex][capacity];
}
console.log(maxKnapsack(weights,profits,capacity,0))