Introduction to Greedy Algorithms (original) (raw)

Last Updated : 26 Jan, 2026

Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems.

An optimization problem can be solved using Greedy if the problem has the following property:

However, it's important to note that not all problems are suitable for greedy algorithms. They work best when the problem exhibits the following properties:

How does a Greedy Algorithm work?

Greedy Algorithmsolve optimization problems by making the **best local choice at each step in the hope of finding the global optimum. It's like taking the best option available at each moment, hoping it will lead to the best overall outcome.

Here's how it works:

  1. Start with the initial state of the problem.
  2. Consider all the options available at that specific moment.
  3. Choose the option that seems best at that moment, regardless of future consequences. This is the "greedy" part - you take the best option available now, even if it might not be the best in the long run.
  4. Move to the new state based on your chosen option. This becomes your new starting point for the next iteration.
  5. Repeat steps 2-4 until you reach the goal state or no further progress is possible.

**Example:

Let's say you have a set of coins with values [1, 2, 5, 10] and you need to give **minimum number of coin to someone change for 39.

The greedy algorithm for making change would work as follows:

Repeat **steps 1 and 2 until the amount to be changed becomes 0.

Below is the illustration of above example:

C++ `

// C++ Program to find the minimum number of coins // to construct a given amount using greedy approach

#include #include #include using namespace std;

int minCoins(vector &coins, int amount) { int n = coins.size(); sort(coins.begin(), coins.end()); int res = 0;

// Start from the coin with highest denomination
for(int i = n - 1; i >= 0; i--) {
    if(amount >= coins[i]) {
      
        // Find the maximum number of ith coin 
        // we can use
        int cnt = (amount / coins[i]);
      
        // Add the count to result
        res += cnt;
      
        // Subtract the corresponding amount from
        // the total amount
        amount -= (cnt * coins[i]);
    }
  
    // Break if there is no amount left
    if(amount == 0)
        break;
}
return res;

}

int main() { vector coins = {5, 2, 10, 1}; int amount = 39;

cout << minCoins(coins, amount);
return 0;

}

C

// C Program to find the minimum number of coins // to construct a given amount using greedy approach

#include <stdio.h> #include <stdlib.h>

int compare(const void *a, const void b) { return ((int *)b - *(int *)a); }

int minCoins(int coins[], int n, int amount) {

// Sort the coins in descending order
qsort(coins, n, sizeof(int), compare);

int res = 0;

// Start from the coin with highest denomination
for(int i = 0; i < n; i++) {
    if(amount >= coins[i]) {
      
        // Find the maximum number of ith coin 
        // we can use
        int cnt = (amount / coins[i]);
      
        // Add the count to result
        res += cnt;
      
        // Subtract the corresponding amount from
        // the total amount
        amount -= (cnt * coins[i]);
    }
  
    // Break if there is no amount left
    if(amount == 0)
        break;
}
return res;

}

int main() { int coins[] = {5, 2, 10, 1}; int n = sizeof(coins) / sizeof(coins[0]); int amount = 39;

printf("%d", minCoins(coins, n, amount));
return 0;

}

Java

// Java Program to find the minimum number of coins // to construct a given amount using greedy approach

import java.util.Arrays;

class GfG { static int minCoins(int[] coins, int amount) { int n = coins.length; Arrays.sort(coins);
int res = 0;

    // Start from the coin with highest denomination
    for (int i = n - 1; i >= 0; i--) {
        if (amount >= coins[i]) {
          
            // Find the maximum number of ith coin we can use
            int cnt = (amount / coins[i]);
            
            // Add the count to result
            res += cnt;
            
            // Subtract the corresponding amount from 
            // the total amount
            amount -= (cnt * coins[i]);
        }
        
        // Break if there is no amount left
        if (amount == 0)
            break;
    }
    return res;
}

public static void main(String[] args) {
    int[] coins = {5, 2, 10, 1};
    int amount = 39;
  
    System.out.println(minCoins(coins, amount));
}

}

Python

Python Program to find the minimum number of coins

to construct a given amount using greedy approach

def minCoins(coins, amount): n = len(coins) coins.sort() res = 0

# Start from the coin with highest denomination
for i in range(n - 1, -1, -1):
    if amount >= coins[i]:
      
        # Find the maximum number of ith coin we can use
        cnt = amount // coins[i]

        # Add the count to result
        res += cnt

        # Subtract the corresponding amount from the total amount
        amount -= cnt * coins[i]

    # Break if there is no amount left
    if amount == 0:
        break
return res

if name == "main": coins = [5, 2, 10, 1] amount = 39

print(minCoins(coins, amount))

C#

// C# Program to find the minimum number of coins // to construct a given amount using greedy approach

using System;

class GfG { static int minCoins(int[] coins, int amount) { int n = coins.Length; Array.Sort(coins); int res = 0;

    // Start from the coin with highest denomination
    for (int i = n - 1; i >= 0; i--) {
        if (amount >= coins[i]) {
          
            // Find the maximum number of ith coin we can use
            int cnt = (amount / coins[i]);

            // Add the count to result
            res += cnt;

            // Subtract the corresponding amount from the total amount
            amount -= (cnt * coins[i]);
        }

        // Break if there is no amount left
        if (amount == 0)
            break;
    }
    return res;
}

static void Main() {
    int[] coins = { 5, 2, 10, 1 };
    int amount = 39;
  
    Console.WriteLine(minCoins(coins, amount));
}

}

JavaScript

// JavaScript Program to find the minimum number of coins // to construct a given amount using greedy approach

function minCoins(coins, amount) { let n = coins.length; coins.sort((a, b) => a - b); let res = 0;

// Start from the coin with highest denomination
for (let i = n - 1; i >= 0; i--) {
    if (amount >= coins[i]) {

        // Find the maximum number of ith coin we can use
        let cnt = Math.floor(amount / coins[i]);

        // Add the count to result
        res += cnt;

        // Subtract the corresponding amount from the total amount
        amount -= (cnt * coins[i]);
    }

    // Break if there is no amount left
    if (amount === 0)
        break;
}
return res;

}

// Driver code let coins = [5, 2, 10, 1]; let amount = 39;

console.log(minCoins(coins, amount));

`

The **greedy algorithm is not always the optimal solution for every optimization problem, as shown in the example below.

However, the greedy approach fails to find the optimal solution in this case. Although it uses three coins, a better solution would have been to use two 10 coins, resulting in a total of only two coins (10 + 10 = 20).

Characteristics of Greedy Algorithm

Here are the characteristics of a greedy algorithm:

These characteristics help to define the nature and usage of greedy algorithms in problem-solving.

**Related Articles: