Skip to content

Commit 2cb5f1e

Browse files
committed
renamed napsack.go to Knapsack.go, changed using struct to using weight, value slice, changed printing all to printing max profit.
1 parent 8ee19d2 commit 2cb5f1e

File tree

2 files changed

+49
-77
lines changed

2 files changed

+49
-77
lines changed

dynamic-programming/knapsack.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Knapsack Problem
2+
// https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
3+
package Knapsack
4+
5+
// package main
6+
7+
import (
8+
"math"
9+
)
10+
11+
func max(a, b int) int {
12+
return int(math.Max(float64(a), float64(b)))
13+
}
14+
15+
// solve knapsack problem
16+
// return maxProfit
17+
func solve(maxWeight int, weights, values []int) int {
18+
n := len(weights)
19+
m := maxWeight
20+
// create dp data structure
21+
dp := make([][]int, n+1)
22+
for i := range dp {
23+
dp[i] = make([]int, m+1)
24+
}
25+
for i := 0; i < len(weights); i++ {
26+
for j := 0; j <= maxWeight; j++ {
27+
if weights[i] > j {
28+
dp[i+1][j] = dp[i][j]
29+
} else {
30+
dp[i+1][j] = max(dp[i][j-weights[i]]+values[i], dp[i][j])
31+
}
32+
}
33+
}
34+
return dp[n][m]
35+
}
36+
37+
/*
38+
func main() {
39+
maxWeight := 50
40+
values := []int{
41+
60, 100, 120,
42+
}
43+
weights := []int{
44+
10, 20, 30,
45+
}
46+
maxProfit := solve(maxWeight, weights, values)
47+
fmt.Println(maxProfit)
48+
}
49+
*/

dynamic-programming/napsack.go

Lines changed: 0 additions & 77 deletions
This file was deleted.

0 commit comments

Comments
 (0)