Skip to content
We areTOP 1%
DSA · Intermediate · Pattern 7 of 10

Greedy

17 problems.
Your progress0%
1st Visit
0/17
2nd Visit
0/17
Revise
0/17

About this pattern

A greedy algorithm makes the locally best choice at each step and never revisits it. It is correct only when an exchange argument holds: any optimal solution can be transformed, without becoming worse, into one that agrees with the greedy choice. Most greedy solutions start by sorting on a well-chosen key, then scan once while maintaining a running state such as the farthest reachable index, the remaining fuel or the last occupied position.

Signals include maximising a count or minimising a cost where choices interact only through simple state. Before coding, try to break your rule with a small counterexample. Typical cost is O(n log n) for sorting plus an O(n) scan.

// Sort by the key that makes the local choice safe, then scan once.
sort(items.begin(), items.end(), [](const Item& x, const Item& y) {
    return x.key < y.key;
});
long long state = initialState, answer = 0;
for (const Item& it : items) {
    if (canTake(state, it)) {        // the greedy decision
        state = update(state, it);
        ++answer;
    }
}

Problems

Greedy questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Assign CookiesLeetCodeEasy Solve Assign Cookies on LeetCode (opens in a new tab)
2Lemonade ChangeLeetCodeEasy Solve Lemonade Change on LeetCode (opens in a new tab)
3BerSU BallCodeforcesEasy 1200Solve BerSU Ball on Codeforces (opens in a new tab)
4Alternating SubsequenceCodeforcesEasy 1200Solve Alternating Subsequence on Codeforces (opens in a new tab)
5Stable GroupsCodeforcesEasy 1200Solve Stable Groups on Codeforces (opens in a new tab)
6Young ExplorersCodeforcesEasy 1200Solve Young Explorers on Codeforces (opens in a new tab)
7Jump GameLeetCodeMedium Solve Jump Game on LeetCode (opens in a new tab)
8Jump Game IILeetCodeMedium Solve Jump Game II on LeetCode (opens in a new tab)
9Gas StationLeetCodeMedium Solve Gas Station on LeetCode (opens in a new tab)
10Partition LabelsLeetCodeMedium Solve Partition Labels on LeetCode (opens in a new tab)
11Social DistanceCodeforcesMedium 1300Solve Social Distance on Codeforces (opens in a new tab)
12QueueCodeforcesMedium 1300Solve Queue on Codeforces (opens in a new tab)
13ExamsCodeforcesMedium 1400Solve Exams on Codeforces (opens in a new tab)
14Given Length and Sum of Digits...CodeforcesMedium 1400Solve Given Length and Sum of Digits... on Codeforces (opens in a new tab)
15Arranging The SheepCodeforcesMedium 1400Solve Arranging The Sheep on Codeforces (opens in a new tab)
16WoodcuttersCodeforcesMedium 1500Solve Woodcutters on Codeforces (opens in a new tab)
17CandyLeetCodeHard Solve Candy on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account