Learn Matrix Chain Multiplication with a step-by-step Dynamic Programming visualizer, JavaScript source code and a worked example. Practice partition and interval dp.
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.
Topic: Dynamic Programming · Partition and interval DP
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
{
"a": [
40,
20,
30,
10,
30
],
"mode": "matrix"
}
Execution steps
Evaluate interval split
Computed output
26000
JavaScript reference implementation
const solve = ({
a,mode
},s)=>{
let n=mode==="matrix"?a.length-1:a.length-2,d=Array.from({
length:n+2
},()=>Array(n+2).fill(0));
for(let len=1;
len<=n;
len++)for(let i=1;
i+len-1<=n;
i++){
let j=i+len-1;
if(mode==="matrix"&&len===1)continue;
let b=mode==="burst"?0:Infinity;
for(let k=i;
k<=(mode==="matrix"?j-1:j);
k++){
let v=mode==="matrix"?d[i][k]+d[k+1][j]+a[i-1]*a[k]*a[j]:d[i][k-1]+d[k+1][j]+(mode==="cut"?a[j+1]-a[i-1]:a[i-1]*a[k]*a[j+1]);
b=mode==="burst"?Math.max(b,v):Math.min(b,v);
s("Evaluate interval split",{
Input:a,DP:d,Interval:[i,k,j],Candidate:[v],Best:[b]
})
}
d[i][j]=b
}
return d[1][n]
};