The greedy method is a powerful algorithm design paradigm used to solve optimization problems. It makes the best choice available at each step, hoping that these locally optimal choices will lead to a globally optimal solution. This approach is often simple to implement but does not always guarantee optimality.
The greedy method is a straightforward technique applicable to a wide variety of problems. For problems involving inputs, where we need to find a subset that satisfies certain conditions, the greedy approach can be highly effective.
A subset that satisfies all problem constraints is called a feasible solution. Among all feasible solutions, we are typically looking for one that either maximizes or minimizes an objective function. This particular feasible solution is known as an optimal solution.
The core idea of the greedy method is to work in stages, considering one input at a time. At each stage, a decision is made to determine if a particular input should be included in the optimal solution. This decision is based on a selection procedure that defines an order for considering inputs and a greedy criterion that dictates the locally optimal choice.
Two key properties usually indicate that a greedy approach might work:
Consider a scenario where you have tasks and an infinite number of machines. Each task has a start time and a finish time , where . The interval represents the processing interval for task . Two tasks, and , are said to overlap if their processing intervals overlap, excluding just touching at an endpoint (e.g., overlaps with but not with ).
A feasible task-to-machine assignment is one where no machine is assigned to two overlapping tasks; that is, each machine handles at most one task at any given time. The objective is to minimize the total number of machines required to complete all tasks.
Greedy Approach for Machine Scheduling:
The greedy strategy for this problem involves:
Let's illustrate with an example: Suppose we have tasks labeled A to G, with their start and finish times:
| Task | Start () | Finish () | | :--- | :----------- | :------------- | | A | 0 | 2 | | B | 3 | 7 | | C | 4 | 7 | | D | 9 | 11 | | E | 7 | 10 | | F | 1 | 5 | | G | 6 | 8 |
Step 1: Sort by Start Time
| Task | Start () | Finish () | | :--- | :----------- | :------------- | | A | 0 | 2 | | F | 1 | 5 | | B | 3 | 7 | | C | 4 | 7 | | G | 6 | 8 | | E | 7 | 10 | | D | 9 | 11 |
Step 2: Assign Tasks
M1 after 2.M1 after 2, M2 after 5.M1 after 7, M2 after 5.M1 after 7, M2 after 5, M3 after 7.M1 after 7, M2 after 8, M3 after 7.M1 after 10, M2 after 8, M3 after 7.M1 after 10, M2 after 11, M3 after 7.Total machines used: 3. This greedy approach often provides an optimal solution for minimizing machines if tasks are scheduled based on earliest finish time availability.
The Fractional Knapsack Problem involves objects, each with a weight and a profit . We have a knapsack with a maximum capacity . The objective is to fill the knapsack such that the total profit is maximized. A key characteristic is that objects can be divided, meaning we can take a fraction (where ) of an object , earning a profit of and consuming weight.
The problem can be formally stated as: Maximize Subject to And , for .
A feasible solution is any set where the total weight is at most . An optimal solution is a feasible solution that yields the maximum possible total profit.
Greedy Approach (Price Per Unit):
The greedy strategy for the Fractional Knapsack Problem is based on the profit-to-weight ratio () of each item.
Example Walkthrough: Let , knapsack capacity kg. Items: | Item | Weight () | Value () | Ratio () | | :--- | :------------- | :------------ | :---------------- | | 1 | 5 | 30 | 6 | | 2 | 10 | 40 | 4 | | 3 | 15 | 45 | 3 | | 4 | 22 | 77 | 3.5 | | 5 | 25 | 90 | 3.6 |
Step 1 & 2: Calculate Ratios and Sort (descending ratio)
| Item | Weight () | Value () | Ratio () | Sorted Order | | :--- | :------------- | :------------ | :---------------- | :----------- | | 1 | 5 | 30 | 6 | 1 | | 5 | 25 | 90 | 3.6 | 2 | | 4 | 22 | 77 | 3.5 | 3 | | 2 | 10 | 40 | 4 | 4 | | 3 | 15 | 45 | 3 | 5 |
Step 3: Fill Knapsack (M=60, P=0)
Optimal solution: for a total profit of .
We are given a set of jobs. Each job has an integer deadline and a profit . The profit is earned only if job is completed by its deadline. Each job requires one unit of time for processing on a single machine. Only one machine is available.
A feasible solution is a subset of jobs such that all jobs in can be completed by their deadlines. The value of a feasible solution is the sum of the profits of all jobs in . An optimal solution is a feasible solution with the maximum possible total profit.
Greedy Approach:
Example: Let jobs.
Step 1: Sort by Profit (descending)
| Job | Profit () | Deadline () | | :-- | :------------- | :--------------- | | J1 | 100 | 2 | | J4 | 27 | 1 | | J3 | 15 | 2 | | J2 | 10 | 1 |
Maximum deadline is 2, so time slots are 1, 2. schedule array will represent slots.
Step 2: Schedule Jobs
schedule[2] = J1. Profit = 100.
schedule = [_, J1]schedule[1] = J4. Profit = .
schedule = [J4, J1]Optimal schedule: J4 at time 1, J1 at time 2. Total profit = 127.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
// Structure to represent a job
struct Job {
char id; // Job ID
int deadline; // Deadline for the job
int profit; // Profit from the job
};
// Comparison function for sorting jobs by profit in descending order
bool compareJobs(const Job& a, const Job& b) {
return a.profit > b.profit;
}
// Function to find the maximum profit and job sequence
std::pair<int, std::vector<char>> jobSequencingWithDeadline(std
Imagine you have programs to store on a computer tape of length . Each program has a length . All programs can be stored if . When a program is retrieved, the tape is initially positioned at the front. Programs can only be retrieved from the front of the tape. If programs are stored in the order , the time to retrieve program is the sum of lengths of programs . The goal is to find an optimal permutation (ordering) for the programs to minimize the .
The retrieval time for program is . The total retrieval time for all programs is . The Mean Retrieval Time (MRT) is .
Greedy Approach:
To minimize MRT, the greedy strategy is to simply store the programs in non-decreasing order of their lengths. That is, the shortest program goes first.
Example: Let programs with lengths .
Step 1: Sort by Length (ascending)
| Program | Length | | :------ | :----- | | 3 | 3 | | 1 | 5 | | 2 | 10 |
Optimal order: (3, 1, 2)
Step 2: Calculate Total Retrieval Time and MRT
Total Retrieval Time = . MRT = .
Let's compare this to other orderings from the source material:
| Order (Sr. No.) | Order | Total Retrieval Time | MRT | | :-------------- | :------- | :------------------- | :------- | | 1 | (1, 2, 3)| | | | 2 | (1, 3, 2)| | | | | | | |
The greedy choice (shortest first) indeed yields the minimum MRT.
When merging multiple sorted files, say , into a single sorted file, we can do this by repeatedly merging two sorted files at a time. The time required to merge two sorted files of lengths and records is . Different sequences of pairwise merges will result in different total comparison counts (or record moves). The problem is to find an optimal merge pattern that minimizes the total number of comparisons.
Greedy Approach:
The greedy strategy is to always combine the two smallest files (in terms of current number of records/length) at each stage. This creates a new merged file, which then replaces the two original files in the pool of files to be merged. This process continues until only one file remains.
Example: Files with lengths .
Method 1 (Non-optimal): Merge and first, then merge result with .
ASCII Art representation:
Y2 (60)
/ \
Y1(50) X3(10)
/ \
X1(30) X2(20)Method 2 (Greedy - Optimal): Merge the two smallest files first.
ASCII Art representation:
Y2 (60)
/ \
X1(30) Y1(30)
/ \
X2(20) X3(10)The greedy method produces a lower total cost. This strategy can be implemented using a min-priority queue to efficiently find the two smallest files.
In telecommunication, it's desirable to represent messages (or symbols) using sequences of 0s and 1s such that frequently used messages have shorter codes, minimizing overall transmission and decoding costs. Huffman coding is a greedy algorithm that constructs such an optimal prefix code. A prefix code ensures that no code for a character is a prefix of the code for another character, allowing unambiguous decoding.
Greedy Approach:
Huffman's algorithm builds an extended binary tree. At each step, it combines the two smallest frequency symbols/nodes into a new parent node, whose frequency is the sum of its children's frequencies. This new node then replaces its children in the set, and the process repeats until only one node (the root of the Huffman tree) remains.
Steps:
x and y).z with frequency . Make and its left and right children (order doesn't matter for optimality, but conventionally (smaller frequency) is left).Example: Symbols: A, B, C, D, E, F, G Frequencies: 2, 3, 5, 8, 13, 15, 18
Initial: (A:2), (B:3), (C:5), (D:8), (E:13), (F:15), (G:18)
The resulting tree (and codes) can be visualized.
(64)
/ \
(28) (36)
/ \ / \
(13) (15) (18) (18)
E F G / \
(8) (10)
D / \
(5) (5)
C / \
(2) (3)
A BFrom this tree, assigning 0 for left and 1 for right: A: 10100 B: 10101 C: 1011 D: 100 E: 00 F: 01 G: 11
A problem exhibits greedy choice property if a globally optimal solution can be reached by making a locally optimal (greedy) choice at each stage, without reconsidering previous choices.
A problem has optimal substructure if an optimal solution to the problem contains optimal solutions to its subproblems, allowing for recursive or iterative construction of the solution.
Any solution to a problem that satisfies all the given constraints, regardless of whether it achieves the best possible objective value.
A feasible solution that achieves the best possible value for the problem's objective function (either maximum profit or minimum cost).
A greedy strategy for assigning tasks to machines involves sorting tasks by their start times and assigning each task to the earliest available machine that can accommodate it, or a new machine if none are available.
Test your understanding with 5 questions
Which of the following is a core characteristic that indicates a problem might be solvable using the greedy method?
Consider a Machine Scheduling problem where tasks have start and finish times. A common greedy strategy is to:
In the Fractional Knapsack Problem, if an item cannot be taken whole due to weight constraints, what fraction of the item should be taken to maximize profit?
Which of the following problems can be optimally solved using a greedy approach by sorting items/jobs by their length or size?
When applying the greedy method to the Optimal Merge Pattern problem (merging multiple sorted files), what is the optimal strategy?
xyxz back to the priority queue.6 Modules
6 Modules