package bagProblem
import "fmt"
func BagProblem1(weight, value []int, bagweight int) int {
dp := make([][]int, len(weight))
for i := 0; i < len(weight); i++ {
dp[i] = make([]int, bagweight+1)
}
for j := 0; j <= bagweight; j++ {
if weight[0] <= j {
dp[0][j] = value[0]
}
}
for i := 1; i < len(weight); i++ {
for j := 1; j <= bagweight; j++ {
if weight[i] > j {
dp[i][j] = dp[i-1][j]
} else {
dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i])
}
}
}
return dp[len(weight)-1][bagweight]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func BagProblem2(weight, value []int, bagweight int) int {
dp := make([]int, bagweight+1)
for i := 0; i < len(weight); i++ {
for j := bagweight; j >= 0; j-- {
fmt.Println(i)
if j < weight[i] {
dp[j] = dp[j]
} else {
dp[j] = max(dp[j], dp[j-weight[i]]+value[i])
}
fmt.Println(dp)
}
}
return dp[bagweight]
}
|