Concepts

Greedy interval scheduling

Try the free JavaScript compiler

A local-choice algorithm is globally optimal only under a problem-specific proof, such as an exchange argument for earliest-finish interval selection.

Formal Syntax & Structure

javascript syntaxjavascript
choose feasible local optimum; update remaining problem

Working Example

Example Snippetjavascript
const intervals=[[0,5],[1,2],[2,3],[3,4]];const selected=[];let end=-Infinity;for(const [s,e] of intervals.toSorted((a,b)=>a[1]-b[1])){  if(s>=end){selected.push([s,e]);end=e;}}console.log(JSON.stringify(selected));
JavaScript Reference