Knowledge Guide
HomeDSAGreedy

Introduction to Greedy Algorithm

Understanding Greedy Algorithm

A Greedy algorithm is used to solve problems in which the best choice is made at each step, and it finds a solution in a minimal step. This approach assumes that choosing a local optimum at each stage will lead to the determination of a global optimum. It's like making the most beneficial decision at every crossroad, hoping it leads to the ultimate destination efficiently.

Purpose of Greedy Algorithm

The main goal of a greedy algorithm is to solve complex problems by breaking them down into simpler subproblems, solving each one optimally to find a solution that is as close as possible to the overall optimum. It's particularly useful in scenarios where the problem exhibits the properties of greedy choice and optimal substructure.

Properties for Greedy Algorithm Suitability

  1. Greedy Choice Property: The local optimal choices lead to a global optimum, meaning the best solution in each small step leads to the best overall solution.
  2. Optimal Substructure: A problem has an optimal substructure if an optimal solution to the entire problem contains the optimal solutions to its subproblems.

Characteristics of Greedy Method

  1. Local Optimization: At every step, the algorithm makes a choice that seems the best at that moment, aiming for local optimality.
  2. Irrevocability: Once a choice is made, it cannot be undone or revisited. This is a key characteristic that differentiates greedy methods from dynamic programming, where decisions can be re-evaluated.

Components of Greedy Algorithm

  1. Candidate Set: The set of choices available at each step.
  2. Selection Function: This function helps in choosing the most promising candidate to be added to the current solution.
  3. Feasibility Function: It checks if a candidate can be used to contribute to a solution without violating problem constraints.
  4. Objective Function: This evaluates the value or quality of the solution at each step.
  5. Solution Function: It determines if a complete solution has been reached.

Simplified Greedy Algorithm Process

  1. Start with an Empty Solution Set: The algorithm begins with no items in the solution set.

  2. Iterative Item Selection: In each step, choose the most suitable item based on the current goal.

  3. Add Item to Solution Set: The selected item is added to the solution set.

  4. Feasibility Check: Determine if the solution set with the new item still meets the problem's constraints.

  5. Accept or Reject the Item:

    • If Feasible: Keep the item in the solution set.
    • If Not Feasible: Remove and permanently discard the item.
  6. Repeat Until Complete: Continue this process until a full solution is formed or no feasible solution can be found.

  7. Assess Final Solution: Evaluate the completed solution set against the problem's objectives.

Let's understand the greedy algorithm via the example below.

Problem Statement (Boats to Save People)

We are given an array people where each element people[i] represents the weight of the i-th person. There is also a weight limit for each boat. Each boat can carry at most two people at a time, but the combined weight of these two people must not exceed limit. The objective is to determine the minimum number of boats required to carry all the people.

Example

Input: people = [10, 55, 70, 20, 90, 85], limit = 100
Output: 4
Explanation: One way to transport all people using 4 boats is as follows:

Algorithm

  1. Sort the Array: Sort the people array in ascending order.
    Arrays.sort(people);
  2. Initialize Two Pointers: Set two pointers, i at the start (lightest person) and j at the end (heaviest person) of the array.
  3. Select Optimal Pairs: Iterate through the array and pair the lightest person with the heaviest person if their combined weight is within the limit.
    if (people[i] + people[j] <= limit) { i++; // Move to the next lightest person }
  4. Count Boats: For each iteration, increment the boat count. Move the j pointer to the left (next heaviest person).
  5. Repeat Until All Are Accounted For: Continue until all people are accounted for (i.e., until i < j).
  6. If i == j, increment the boat count by 1 to arrange boat for last remaining person.
  7. Return the Boat Count: The total count of boats is the minimum number required.

Algorithm Walkthrough

Image
Image

Code

java
import java.util.Arrays;

public class Solution {

  public int numRescueBoats(int[] people, int limit) {
    Arrays.sort(people); // Sort the array in ascending order
    int i = 0; // Pointer for the lightest person
    int j = people.length - 1; // Pointer for the heaviest person
    int boats = 0; // Count of boats

    while (i < j) {
      if (people[i] + people[j] <= limit) {
        // If the lightest and heaviest person can share a boat
        i++; // Move to the next lightest person
      }
      j--; // Move to the next heaviest person
      boats++; // Increment boat count
    }
    // When last person is left.
    if (i == j) {
      boats++;
    }
    return boats; // Return the total number of boats needed
  }

  public static void main(String[] args) {
    Solution solution = new Solution();
    int[] people = { 10, 55, 70, 20, 90, 85 };
    int limit = 100;

    int result = solution.numRescueBoats(people, limit);
    System.out.println("Minimum number of boats required: " + result);
    // Expected output: "Minimum number of boats required: 2"
  }
}

In the above problem, the greedy approach is applied through the strategy of pairing the lightest and heaviest individuals to optimize boat usage. After sorting the people by weight, the algorithm iteratively pairs the lightest person (at the start of the array) with the heaviest (at the end), maximizing the use of each boat's capacity. This method ensures that each boat carries as much weight as possible without exceeding the limit, effectively reducing the total number of boats needed.

The essence of the greedy method here is making the most efficient pairing choice at each step, aiming for an overall optimal solution - the minimum number of boats to transport everyone.

Pros of Greedy Approach

Cons of Greedy Approach with Example

         2
       /   \
      1     3
     / \     \
   20   8     7

In the given tree, a greedy approach, which selects the path with the highest immediate weight at each step, would choose the path 2 → 3 → 7, resulting in a total weight of 12.

However, this is not the optimal path. The path 2 → 1 → 20, although starting with a lower weight at the first decision point, leads to a higher total weight of 23. This example demonstrates how the greedy approach can fail to find the best solution, as it overlooks the long-term benefits of initially less attractive choices.

Standard Greedy Algorithms

Let's start solving the problem which are based on the greedy algorithm.

🤖 Don't fully get this? Learn it with Claude

Stuck on Introduction to Greedy Algorithm? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Introduction to Greedy Algorithm** (DSA) and want to truly understand it. Explain Introduction to Greedy Algorithm from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Introduction to Greedy Algorithm** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Introduction to Greedy Algorithm** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Introduction to Greedy Algorithm** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes