Workspace 0 1 Knapsack
0d
Back to questionsDSA Visualizers: 388 Coding Questions

0 1 Knapsack visualizer

Learn 0 1 Knapsack with a step-by-step Dynamic Programming visualizer, JavaScript source code and a worked example. Practice subsequences and knapsack.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 5Execution step
Reference example · JavaScript
Inspect reference input
{
  "weights": [
    1,
    3,
    4,
    5
  ],
  "values": [
    1,
    4,
    5,
    7
  ],
  "k": 7,
  "repeat": false
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
weights,values,k,repeat
},s)=>{
let d=Array(k+1).fill(0);
for(let i=0;
i<weights.length;
i++){
let w=weights[i],v=values[i];
if(repeat){
for(let j=w;
j<=k;
j++)d[j]=Math.max(d[j],v+d[j-w])
}else{
for(let j=k;
j>=w;
j--)d[j]=Math.max(d[j],v+d[j-w])
}
s("Update capacities for item "+i,{
Weights:weights,Values:values,DP:d
})
}
return d[k]
};

Execution canvas

Active Changed
STEP 1

Update capacities for item 0

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Weights4 items
Values4 items
DP8 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Dynamic Programming · Subsequences and knapsack

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

{
  "weights": [
    1,
    3,
    4,
    5
  ],
  "values": [
    1,
    4,
    5,
    7
  ],
  "k": 7,
  "repeat": false
}

Execution steps

  1. Update capacities for item 0
  2. Update capacities for item 1
  3. Update capacities for item 2
  4. Update capacities for item 3

Computed output

9
JavaScript reference implementation
const solve = ({
  weights,values,k,repeat
},s)=>{
  let d=Array(k+1).fill(0);
  for(let i=0;
  i<weights.length;
  i++){
    let w=weights[i],v=values[i];
    if(repeat){
      for(let j=w;
      j<=k;
      j++)d[j]=Math.max(d[j],v+d[j-w])
    }else{
      for(let j=k;
      j>=w;
      j--)d[j]=Math.max(d[j],v+d[j-w])
    }
    s("Update capacities for item "+i,{
      Weights:weights,Values:values,DP:d
    })
  }
  return d[k]
};

Continue learning

Practice related DSA questions in the same topic.