Skip to content
DSA in JavaScript
← All patterns

Greedy

0/14 solved

What it is

At each step take the choice that looks best right now and never revisit it. It works when a local best always leads to a global best.

Used for

Scheduling, jump game, gas station, interval selection, coin change with special coins.
jump
2↑ start
3
1
1
4

Step 1 of 5

Goal: can you reach the last cell if each number is the farthest you may jump from that cell? Idea: only track the farthest cell you could possibly reach so far. Never try individual routes.

You see

  • A locally best choice is globally safe
  • Reach, schedule or cover problems
  • Sorting first makes the choice obvious

Learn it in

Pascal's TriangleJump GameKruskal's AlgorithmPrim's Algorithm

Template

function canJump(nums) {  let reach = 0;  for (let i = 0; i < nums.length; i++) {    if (i > reach) return false;    reach = Math.max(reach, i + nums[i]);  }  return true;}

Practice problems