Workspace Largest Divisible Subset
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Largest Divisible Subset visualizer

Learn Largest Divisible Subset with a step-by-step Dynamic Programming visualizer, JavaScript source code and a worked example. Practice stocks and increasing subsequences.

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
{
  "a": [
    1,
    2,
    4,
    8
  ],
  "mode": "div"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,mode
},s)=>{
if(mode==="div")a.sort((x,y)=>x-y);
let d=a.map(()=>1),p=a.map((_,i)=>i),c=a.map(()=>1);
for(let i=0;
i<a.length;
i++){
for(let j=0;
j<i;
j++)if(mode==="div"?a[i]%a[j]===0:a[j]<a[i]){
if(d[j]+1>d[i]){
d[i]=d[j]+1;
p[i]=j;
c[i]=c[j]
}else if(d[j]+1===d[i])c[i]+=c[j]
}
s("Extend valid predecessor chains",{
Array:a,DP:d,Parents:p,Counts:c
},[i])
}
let max=Math.max(...d);
if(mode==="count")return c.reduce((n,x,i)=>n+(d[i]===max?x:0),0);
let i=d.indexOf(max),o=[a[i]];
while(p[i]!==i){
i=p[i];
o.unshift(a[i])
}
return o
};

Execution canvas

Active Changed
STEP 1

Extend valid predecessor chains

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

Array4 items
DP4 items
Parents4 items
Counts4 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Dynamic Programming · Stocks and increasing subsequences

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": [
    1,
    2,
    4,
    8
  ],
  "mode": "div"
}

Execution steps

  1. Extend valid predecessor chains

Computed output

[
  1,
  2,
  4,
  8
]
JavaScript reference implementation
const solve = ({
  a,mode
},s)=>{
  if(mode==="div")a.sort((x,y)=>x-y);
  let d=a.map(()=>1),p=a.map((_,i)=>i),c=a.map(()=>1);
  for(let i=0;
  i<a.length;
  i++){
    for(let j=0;
    j<i;
    j++)if(mode==="div"?a[i]%a[j]===0:a[j]<a[i]){
      if(d[j]+1>d[i]){
        d[i]=d[j]+1;
        p[i]=j;
        c[i]=c[j]
      }else if(d[j]+1===d[i])c[i]+=c[j]
    }
    s("Extend valid predecessor chains",{
      Array:a,DP:d,Parents:p,Counts:c
    },[i])
  }
  let max=Math.max(...d);
  if(mode==="count")return c.reduce((n,x,i)=>n+(d[i]===max?x:0),0);
  let i=d.indexOf(max),o=[a[i]];
  while(p[i]!==i){
    i=p[i];
    o.unshift(a[i])
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.