Workspace Partition Array For Maximum Sum
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Partition Array for Maximum Sum visualizer

Learn Partition Array for Maximum Sum 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.

1 / 19Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    15,
    7,
    9,
    2,
    5,
    10
  ],
  "k": 3
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let d=Array(a.length+1).fill(0);
for(let i=1;
i<=a.length;
i++){
let m=0;
for(let j=1;
j<=k&&j<=i;
j++){
m=Math.max(m,a[i-j]);
d[i]=Math.max(d[i],d[i-j]+m*j);
s("Choose final block length",{
Array:a,DP:d,Block:[i-j,i-1]
})
}
}
return d.at(-1)
};

Execution canvas

Active Changed
STEP 1

Choose final block length

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

Array7 items
DP8 items
Block2 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

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": [
    1,
    15,
    7,
    9,
    2,
    5,
    10
  ],
  "k": 3
}

Execution steps

  1. Choose final block length

Computed output

84
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let d=Array(a.length+1).fill(0);
  for(let i=1;
  i<=a.length;
  i++){
    let m=0;
    for(let j=1;
    j<=k&&j<=i;
    j++){
      m=Math.max(m,a[i-j]);
      d[i]=Math.max(d[i],d[i-j]+m*j);
      s("Choose final block length",{
        Array:a,DP:d,Block:[i-j,i-1]
      })
    }
  }
  return d.at(-1)
};

Continue learning

Practice related DSA questions in the same topic.