Workspace Minimize Maximum Distance To Gas Station
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Minimize Maximum Distance to Gas Station visualizer

Learn Minimize Maximum Distance to Gas Station with a step-by-step Binary Search visualizer, JavaScript source code and a worked example. Practice search on answer.

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 / 36Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    0,
    10
  ],
  "k": 1
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let l=0,r=a.at(-1)-a[0];
for(let i=0;
i<35;
i++){
let m=(l+r)/2,n=0;
for(let j=1;
j<a.length;
j++)n+=Math.max(0,Math.ceil((a[j]-a[j-1])/m-1e-10)-1);
s("Estimate additional stations",{
Stations:a,Bounds:[l,m,r].map(x=>+x.toFixed(5)),Needed:[n]
});
if(n<=k)r=m;
else l=m
}
return +r.toFixed(5)
};

Execution canvas

Active Changed
STEP 1

Estimate additional stations

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

Stations2 items
Bounds3 items
Needed1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Binary Search · Search on answer

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": [
    0,
    10
  ],
  "k": 1
}

Execution steps

  1. Estimate additional stations

Computed output

5
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let l=0,r=a.at(-1)-a[0];
  for(let i=0;
  i<35;
  i++){
    let m=(l+r)/2,n=0;
    for(let j=1;
    j<a.length;
    j++)n+=Math.max(0,Math.ceil((a[j]-a[j-1])/m-1e-10)-1);
    s("Estimate additional stations",{
      Stations:a,Bounds:[l,m,r].map(x=>+x.toFixed(5)),Needed:[n]
    });
    if(n<=k)r=m;
    else l=m
  }
  return +r.toFixed(5)
};

Continue learning

Practice related DSA questions in the same topic.