Workspace Best Time To Buy And Sell Stock Iii
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Best Time to Buy and Sell Stock III visualizer

Learn Best Time to Buy and Sell Stock III 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 / 9Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    3,
    3,
    5,
    0,
    0,
    3,
    1,
    4
  ],
  "k": 2,
  "fee": 0,
  "cool": 0
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,fee,cool
},s)=>{
let n=a.length,d=Array.from({
length:n+cool+2
},()=>Array.from({
length:k+1
},()=>[0,0]));
for(let i=n-1;
i>=0;
i--){
for(let j=1;
j<=k;
j++){
d[i][j][0]=Math.max(d[i+1][j][0],-a[i]+d[i+1][j][1]);
d[i][j][1]=Math.max(d[i+1][j][1],a[i]-fee+d[i+1+cool][j-1][0])
}
s("Choose buy, sell or wait",{
Prices:a,DP:d[i],Day:[i]
})
}
return d[0][k][0]
};

Execution canvas

Active Changed
STEP 1

Choose buy, sell or wait

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

Prices8 items
DP3 rows
Day1 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": [
    3,
    3,
    5,
    0,
    0,
    3,
    1,
    4
  ],
  "k": 2,
  "fee": 0,
  "cool": 0
}

Execution steps

  1. Choose buy, sell or wait

Computed output

6
JavaScript reference implementation
const solve = ({
  a,k,fee,cool
},s)=>{
  let n=a.length,d=Array.from({
    length:n+cool+2
  },()=>Array.from({
    length:k+1
  },()=>[0,0]));
  for(let i=n-1;
  i>=0;
  i--){
    for(let j=1;
    j<=k;
    j++){
      d[i][j][0]=Math.max(d[i+1][j][0],-a[i]+d[i+1][j][1]);
      d[i][j][1]=Math.max(d[i+1][j][1],a[i]-fee+d[i+1+cool][j-1][0])
    }
    s("Choose buy, sell or wait",{
      Prices:a,DP:d[i],Day:[i]
    })
  }
  return d[0][k][0]
};

Continue learning

Practice related DSA questions in the same topic.