Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    DSADSA

    Foundations: measuring code

    • Big-O: how code grows
    • Space and the time–memory trade-off
    • Arrays and strings under the hood
    • Hash maps and sets
    • How to approach any interview problem

    Array patterns

    • Two pointers
    • Sliding window
    • Prefix sums
    • Binary search, done right
    • Sorting: merge sort and quicksort

    Stacks, queues and linked lists

    • Stacks and monotonic stacks
    • Queues and deques
    • Linked lists

    Recursion and trees

    • Recursion without fear
    • Backtracking: try and undo
    • Binary trees
    • Binary search trees
    • Heaps and priority queues

    Graphs and dynamic programming

    • Graphs: BFS and DFS
    • Shortest paths, topological sort and union-find
    • Dynamic programming: the idea
    • DP on grids and strings
    • Greedy: the best choice right now
    DSA

    Graphs and dynamic programming · Lesson 23 of 23

    Greedy: the best choice right now

    When the locally best choice leads to the global best, and how to be sure.

    12 minutes2 games

    Greedy picks what looks best at each step and never revisits it. When it works it's the fastest, simplest solution (often O(n), or O(n log n) with sorting). The catch: it's not always right, so you need a justification.

    JavaScript
    // Interval scheduling: the most meetings in one room.
    // Greedy rule: always take the meeting that ENDS first.
    function maxMeetings(meetings) {
      const sorted = [...meetings].sort((a, b) => a[1] - b[1])
      let count = 0, freeAt = -Infinity
      for (const [start, end] of sorted) {
        if (start >= freeAt) { count++; freeAt = end }
      }
      return count
    }
    
    console.log(maxMeetings([[1, 4], [2, 3], [3, 5], [7, 9], [5, 8]]))
    
    // Jump game: can you reach the end? Track the farthest reachable index.
    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
    }
    
    console.log(canJump([2, 3, 1, 1, 4]), canJump([3, 2, 1, 0, 4]))
    MeetingEndsTaken?

    [2, 3]

    3

    Yes (ends first)

    [1, 4]

    4

    No, starts before 3

    [3, 5]

    5

    Yes

    [5, 8]

    8

    Yes

    [7, 9]

    9

    No, starts before 8

    Three meetings. Taking the earliest finisher leaves the most free time for the rest.

    How do you know greedy is right?

    The exchange argument: suppose a better solution doesn't start with your choice. Swap its first choice for yours; if it stays valid and no worse, your choice is safe. With meetings: any better schedule can swap its first meeting for the earliest finisher, which ends no later, so it can't clash with the rest.

    Conversely, try small examples. A single counterexample is enough to move on to DP.

    Important

    Famous wrong greedies: sorting meetings by shortest duration or earliest start; both have counterexamples. With coins, greedy (take the largest) works for 1, 5, 10, 25 but fails for [1, 3, 4] and amount 6. Never assume it works without checking.

    Quick question

    Coins [1, 3, 4], amount 6. How many coins does greedy (take the largest that fits) use?

    Interview question

    Why does sorting meetings by end time give the most meetings?

    Exercise

    Write bestProfit(prices): the most profit from buying and selling any number of times (holding at most one share at a time). It must print 7 0.

    Expected output: 7 0

    JavaScript
    function bestProfit(prices) {
      
    }
    
    console.log(bestProfit([7, 1, 5, 3, 6, 4]), bestProfit([7, 6, 4, 3, 1]))

    Practise on real problems

    Practice problems that use what you learned here. Solve them in JavaScript, Python or C++.

    • Jump gameMedium
    • Fewest intervals to removeMedium
    • Meeting rooms neededMedium
    • Gas stationMedium
    • Best time to buy and sellEasy
    • Task scheduler with cooldownMedium
    • Largest water containerMedium

    Learn more from

    • Wikipedia: Greedy algorithmen.wikipedia.org
    • Wikipedia: Interval schedulingen.wikipedia.org
    • Princeton Algorithms: Minimum Spanning Treesalgs4.cs.princeton.edu

    Played 0 of 2 games

    Sign in to save your progress and earn XP.

    PreviousDP on grids and strings🎉 خلّصت DSA!
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.