Knapsack 01 Dynamic Programming (Go)
Solve the 0-1 knapsack problem in Go using dynamic programming with a rolling array for space optimization.
Code
package main
func knapsack01(weights, values []int, capacity int) int {
n := len(weights)
dp := make([]int, capacity+1)
for i := 0; i < n; i++ {
next := make([]int, capacity+1)
for w := 0; w <= capacity; w++ {
next[w] = dp[w]
if w >= weights[i] && dp[w-weights[i]]+values[i] > next[w] {
next[w] = dp[w-weights[i]] + values[i]
}
}
dp = next
}
return dp[capacity]
}The route the data takes
Knapsack 01 Dynamic Programming (Go) comes down to the function knapsack01.
Repetition is confined to for i := 0; i < n; i++ — the rest of the file is straight-line.
Using it
The entry-point signature is func knapsack01(weights, values []int, capacity int) int
Key statements
next := make([]int, capacity+1)
dp := make([]int, capacity+1)
return dp[capacity]
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `knapsack01` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.