Knapsack 01 Dynamic Programming (Rust)

Solve the 0-1 knapsack problem in Rust using dynamic programming with a rolling vector for space optimization.

RustData Integrity

Code

rustsnippet
15 lines
fn knapsack01(weights: &[i32], values: &[i32], capacity: i32) -> i32 {
    let n = weights.len();
    let mut dp = vec![0i32; (capacity + 1) as usize];
    for i in 0..n {
        let mut next = vec![0i32; (capacity + 1) as usize];
        for w in 0..=capacity {
            next[w as usize] = dp[w as usize];
            if w >= weights[i] && dp[(w - weights[i]) as usize] + values[i] > next[w as usize] {
                next[w as usize] = dp[(w - weights[i]) as usize] + values[i];
            }
        }
        dp = next;
    }
    dp[capacity as usize]
}

How it works

Knapsack 01 Dynamic Programming (Rust) keeps everything in the function knapsack01.

The loop for i in 0..n is the only repeated construct.

Applying it

The primary signature is fn knapsack01(weights: &[i32], values: &[i32], capacity: i32) -> i32

knapsack01 is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

next[w as usize] = dp[(w - weights[i]) as usize] + values[i];

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `knapsack01` at load time.