Workspace Cherry Pickup Ii
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Cherry Pickup II visualizer

Learn Cherry Pickup II with a step-by-step Dynamic Programming visualizer, JavaScript source code and a worked example. Practice grid 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 / 5Execution step
Reference example · JavaScript
Inspect reference input
[
  [
    3,
    1,
    1
  ],
  [
    2,
    5,
    1
  ],
  [
    1,
    5,
    5
  ],
  [
    2,
    1,
    1
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let n=a[0].length,d=Array.from({
length:n
},()=>Array(n).fill(0));
for(let i=a.length-1;
i>=0;
i--){
let next=Array.from({
length:n
},()=>Array(n).fill(0));
for(let j=0;
j<n;
j++)for(let k=0;
k<n;
k++){
let b=-Infinity;
for(let x=Math.max(0,j-1);
x<=Math.min(n-1,j+1);
x++)for(let y=Math.max(0,k-1);
y<=Math.min(n-1,k+1);
y++)b=Math.max(b,d[x][y]);
next[j][k]=a[i][j]+(j===k?0:a[i][k])+b
}
s("Combine both robots' possible columns",{
Grid:a,DP:next,Row:[i]
});
d=next
}
return d[0][n-1]
};

Execution canvas

Active Changed
STEP 1

Combine both robots' possible columns

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

Grid4 rows
DP3 rows
Row1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Dynamic Programming · Grid 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

[
  [
    3,
    1,
    1
  ],
  [
    2,
    5,
    1
  ],
  [
    1,
    5,
    5
  ],
  [
    2,
    1,
    1
  ]
]

Execution steps

  1. Combine both robots' possible columns

Computed output

24
JavaScript reference implementation
const solve = (a,s)=>{
  let n=a[0].length,d=Array.from({
    length:n
  },()=>Array(n).fill(0));
  for(let i=a.length-1;
  i>=0;
  i--){
    let next=Array.from({
      length:n
    },()=>Array(n).fill(0));
    for(let j=0;
    j<n;
    j++)for(let k=0;
    k<n;
    k++){
      let b=-Infinity;
      for(let x=Math.max(0,j-1);
      x<=Math.min(n-1,j+1);
      x++)for(let y=Math.max(0,k-1);
      y<=Math.min(n-1,k+1);
      y++)b=Math.max(b,d[x][y]);
      next[j][k]=a[i][j]+(j===k?0:a[i][k])+b
    }
    s("Combine both robots' possible columns",{
      Grid:a,DP:next,Row:[i]
    });
    d=next
  }
  return d[0][n-1]
};

Continue learning

Practice related DSA questions in the same topic.