Workspace Maximum Product Subarray
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Maximum Product Subarray visualizer

Learn Maximum Product Subarray with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

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 / 4Execution step
Reference example · JavaScript
Inspect reference input
[
  2,
  3,
  -2,
  4
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let h=a[0],l=h,b=h;
for(let i=1;
i<a.length;
i++){
let x=a[i];
[h,l]=[Math.max(x,h*x,l*x),Math.min(x,h*x,l*x)];
b=Math.max(b,h);
s("Track extreme products",{
Array:a,Max:[h],Min:[l],Best:[b]
},[i])
}
return b
};

Execution canvas

Active Changed
STEP 1

Track extreme products

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

Array4 items
Max1 items
Min1 items
Best1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

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

[
  2,
  3,
  -2,
  4
]

Execution steps

  1. Track extreme products

Computed output

6
JavaScript reference implementation
const solve = (a,s)=>{
  let h=a[0],l=h,b=h;
  for(let i=1;
  i<a.length;
  i++){
    let x=a[i];
    [h,l]=[Math.max(x,h*x,l*x),Math.min(x,h*x,l*x)];
    b=Math.max(b,h);
    s("Track extreme products",{
      Array:a,Max:[h],Min:[l],Best:[b]
    },[i])
  }
  return b
};

Continue learning

Practice related DSA questions in the same topic.