Back to questionsDSA Visualizers: 388 Coding Questions Rod Cutting visualizer Learn Rod Cutting with a step-by-step Dynamic Programming visualizer, JavaScript source code and a worked example. Practice subsequences and knapsack.
INTERACTIVE EXECUTION STUDIOLEARN BY DOING Predict. Execute. Understand. Follow the source code, inspect live state changes, and predict the next operation before revealing it.
1 / 5 Execution step
Prediction modePanel width Reference example · JavaScript
Inspect reference input {
"weights": [
1,
2,
3,
4
],
"values": [
2,
5,
7,
8
],
"k": 4,
"repeat": true
} Code Visuals
JavaScript reference implementation · highlighted trace statement
1 const solve = ({
2 weights,values,k,repeat
3 },s)=>{
4 let d=Array(k+1 ).fill(0 );
5 for (let i=0 ;
6 i<weights.length;
7 i++){
8 let w=weights[i],v=values[i];
9 if (repeat){
10 for (let j=w;
11 j<=k;
12 j++)d[j]=Math.max(d[j],v+d[j-w])
13 }else {
14 for (let j=k;
15 j>=w;
16 j--)d[j]=Math.max(d[j],v+d[j-w])
17 }
18 s("Update capacities for item "+i,{
19 Weights:weights,Values:values,DP:d
20 })
21 }
22 return d[k]
23 };
Execution canvas Active ChangedSTEP 1 Update capacities for item 0 Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.
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,
2,
3,
4
],
"values": [
2,
5,
7,
8
],
"k": 4,
"repeat": true
} Execution steps Update capacities for item 0 Update capacities for item 1 Update capacities for item 2 Update capacities for item 3 Computed output 10 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.