What greedy means
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A greedy algorithm builds a solution by choosing the best immediate option at each step.
The greedy principle and local choices
A greedy algorithm builds the answer by always taking the choice that looks best right now, without going back. It is correct only when such local choices lead to the best overall answer.
Greedy algorithms make the locally optimal choice at each decision point. They never backtrack or reconsider choices made in previous steps. Brute force search explores all combinations, costing exponential time.
Step by step
Step 1 of 5
- remaining
- 2
- coinsUsed
- 1
Example 1 · Assign Laptops to Employees
import java.util.Arrays;
public class AssignLaptopsDemo { public static int countAssigned(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int employee = 0; int laptop = 0; while (employee < g.length && laptop < s.length) { if (s[laptop] >= g[employee]) { employee++; } laptop++; } return employee; }
public static void main(String[] args) { int[] needs = {1, 2, 3}; int[] laptops = {1, 1}; System.out.println("Satisfied: " + countAssigned(needs, laptops));
int[] greed2 = {1, 2}; int[] laptops2 = {1, 2, 3}; System.out.println("Satisfied: " + countAssigned(greed2, laptops2)); }}Satisfied: 1 Satisfied: 2
What this code does
- Sorts both required specs and laptop sizes in ascending order.
- Gives the smallest acceptable laptop to the least demanding employee.
- Saves larger laptops for employees with higher required specs.
Example 2 · Ticket Counter Change Decision
public class TicketChangeDemo { public static boolean ticketChange(int[] bills) { int five = 0; int ten = 0; for (int bill : bills) { if (bill == 5) { five++; } else if (bill == 10) { if (five == 0) return false; five--; ten++; } else { // bill is 20: prefer giving one 10 and one 5 if (ten > 0 && five > 0) { ten--; five--; } else if (five >= 3) { five -= 3; } else { return false; } } } return true; }
public static void main(String[] args) { int[] order1 = {5, 5, 5, 10, 20}; int[] order2 = {5, 5, 10, 10, 20}; System.out.println("Order 1 valid: " + ticketChange(order1)); System.out.println("Order 2 valid: " + ticketChange(order2)); }}Order 1 valid: true Order 2 valid: false
What this code does
- A five-dollar bill is more versatile than a ten-dollar bill for giving change.
- When returning fifteen dollars, greedily prioritises giving one ten and one five.
- Preserving five-dollar bills prevents running out of change on future ten-dollar bills.
Greedy requires two key properties to guarantee a globally optimal answer. The first property is the greedy choice property. A global optimum can be reached by choosing immediate local advantages. The second property is optimal substructure. An optimal solution contains optimal solutions to its smaller subproblems. When both properties hold, greedy runs much faster than exhaustive search. Sorting or priority queues usually order the candidate choices efficiently. Typical greedy solutions run in linear or log-linear time.
Where greedy fails and counter-examples
Greedy choices are short-sighted because they ignore future trade-offs. A high immediate gain can block an even better combination later. Always test a greedy idea against small counter-examples before coding.
Example 3 · Coin Change Greedy Versus Optimal
import java.util.Arrays;
public class GreedyCoinChangeDemo { public static int greedyCoins(int[] coins, int amount) { Arrays.sort(coins); int count = 0; for (int i = coins.length - 1; i >= 0; i--) { while (amount >= coins[i]) { amount -= coins[i]; count++; } } return amount == 0 ? count : -1; }
public static int optimalCoins(int[] coins, int amount) { int[] dp = new int[amount + 1]; Arrays.fill(dp, amount + 1); dp[0] = 0; for (int a = 1; a <= amount; a++) { for (int c : coins) { if (a >= c) { dp[a] = Math.min(dp[a], dp[a - c] + 1); } } } return dp[amount] > amount ? -1 : dp[amount]; }
public static void main(String[] args) { int[] standard = {25, 10, 5, 1}; System.out.println("Standard 41 cents greedy: " + greedyCoins(standard, 41));
int[] custom = {1, 3, 4}; System.out.println("Custom 6 cents greedy: " + greedyCoins(custom, 6)); System.out.println("Custom 6 cents optimal: " + optimalCoins(custom, 6)); }}Standard 41 cents greedy: 4 Custom 6 cents greedy: 3 Custom 6 cents optimal: 2
What this code does
- Standard denominations 25, 10, 5, 1 yield optimal results with greedy selection.
- Custom coins 1, 3, 4 cause greedy to pick 3 coins instead of 2.
- Demonstrates why greedy requires mathematical proof or canonical currency properties.
Consider the classic coin change problem with denominations 1, 3, and 4. Suppose we need to make change for a value of 6. A greedy strategy picks the largest coin 4 first. That leaves a remainder of 2, requiring two 1-value coins. The greedy result uses three coins: 4, 1, and 1. However, two 3-value coins produce 6 using only two coins. The greedy choice failed because picking 4 broke the optimal pairing. When greedy fails, dynamic programming or backtracking is required instead.
Predict the output
Predict the greedy coins
Read the code and pick what it prints.
Coins are 4, 3 and 1, and we pay 6. What does this program print?
The exchange argument and proof intuition
The exchange argument is a standard method to prove greedy correctness. We assume an optimal solution exists that differs from our greedy solution. We locate the first position where the two solutions make different choices.
Next, we swap the alternative choice with our greedy choice. We prove that this exchange never degrades the quality of the solution. The new solution remains valid and achieves equal or better value.
Repeating this exchange gradually transforms the hypothetical optimum into our greedy result. Because no exchange reduced the score, our greedy solution must be optimal. If an exchange can reduce the score, greedy is flawed.
Next step
Check your understanding
10 quick questions