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

snippet
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]
}