Greedy Algorithm-(Theory)


What is Greedy Algorithm?

A Greedy Algorithm is a problem-solving paradigm where we build up a solution piece by piece, always choosing the option that offers the most immediate benefit (greedy choice). The hope is that this local optimum leads to a global optimum.


Core Properties of a Greedy Algorithm

For a problem to be solved using a greedy approach, it must have:

  1. Greedy Choice Property
    A global optimal solution can be arrived at by choosing a local optimum at each step.

  2. Optimal Substructure
    A problem has an optimal substructure if an optimal solution to the problem contains optimal solutions to its subproblems.


Process to Solve a Problem Using Greedy

To apply greedy strategy correctly:

Step 1: Identify the Greedy Choice Criteria

Step 2: Sort/Arrange the Data

Step 3: Traverse and Make Optimal Local Decisions

Step 4: Ensure Constraints are Satisfied


Common Patterns in Greedy Algorithms


1. Activity Selection Pattern

Problem: Leetcode: 435. Non-overlapping Intervals


2. Interval Scheduling / Meeting Rooms Pattern

Problem: Leetcode: 253. Meeting Rooms II


3. Fractional Knapsack Pattern

Problem: GFG: Fractional Knapsack


4. Job Sequencing Pattern

Problem: GFG: Job Sequencing Problem


5. Huffman Encoding / Compression

📌 Problem: GFG: Huffman Encoding


6. Greedy Coin Change (NOT for all cases)

Only works when denominations are canonical (like INR, USD). For arbitrary denominations, use DP.

Problem: GFG: Coin Change using Greedy


7. Gas Station / Circular Tour

📌 Problem: Leetcode: 134. Gas Station


8. Jump Game

📌 Problem: Leetcode: 55. Jump Game


9. Greedy for Sorting / Swaps

Problem: Leetcode: 670. Maximum Swap


General Template for Greedy Problems

// 1. Define the structure (if needed)
class Pair {
    int value, weight; // or other attributes
    double ratio;
}

// 2. Sort based on greedy criteria
Arrays.sort(arr, (a, b) -> Double.compare(b.ratio, a.ratio)); // descending

// 3. Traverse and apply local optimum
for (Pair item : arr) {
    if (condition) {
        // choose item
    }
}

Greedy vs Dynamic Programming (DP)

Feature Greedy Dynamic Programming
Local vs Global Opt. Local (hopes it leads to global) Global (considers all subproblems)
Time Complexity Usually better (O(n log n) or O(n)) Higher (O(n²) or more)
Space Complexity Low High
Use When Greedy choice + optimal substructure Overlapping subproblems
Example Fractional Knapsack 0/1 Knapsack

Pitfalls


Practice Problems

Problem Name Platform Key Pattern
Minimum Number of Arrows to Burst Balloons Leetcode 452 Interval merge
Lemonade Change Leetcode 860 Greedy denomination exchange
Partition Labels Leetcode 763 Max range from char frequencies
Merge Triplets to Form Target Triplet Leetcode 1899 Component-wise greedy
Reorganize String Leetcode 767 Greedy + Heap

🔚 Conclusion