Skip to content
ajdevhub
1 min read

🌿 Greedy Algorithms

Greedy algorithms make the locally optimal choice at each step, hoping it leads to a globally optimal solution. They work when the problem has greedy choice property and optimal substructure.


Core Patterns

PatternApproachExample
Sort firstSort by key, then greedily pickInterval scheduling, fractional knapsack
Interval schedulingSort by end time, greedily pick non-overlappingActivity selection, meeting rooms
Two-pass greedyForward pass + backward passCandy distribution, temperature ratings
Jump/reach trackingTrack max reachable indexJump Game
Local β†’ GlobalProve local optimum = global optimumGas station circuit

Templates

// Interval scheduling β€” non-overlapping intervals (sort by end time)
sort(intervals.begin(), intervals.end(),
     [](auto& a, auto& b){ return a[1] < b[1]; });
int count = 0, end = INT_MIN;
for (auto& iv : intervals) {
    if (iv[0] >= end) { count++; end = iv[1]; }
}

// Jump Game β€” max reachable index
int maxReach = 0;
for (int i = 0; i <= maxReach && i < n; i++)
    maxReach = max(maxReach, i + nums[i]);
return maxReach >= n - 1;

// Two-pass greedy (Candy)
vector<int> candy(n, 1);
for (int i = 1; i < n; i++)         // left to right
    if (ratings[i] > ratings[i-1]) candy[i] = candy[i-1] + 1;
for (int i = n-2; i >= 0; i--)      // right to left
    if (ratings[i] > ratings[i+1]) candy[i] = max(candy[i], candy[i+1] + 1);

Complexity

PatternTimeSpace
Sort-based greedyO(n log n)O(1)
Linear scan greedyO(n)O(1)
Two-pass greedyO(n)O(n)