0% found this document useful (0 votes)
17 views70 pages

Aa Eth Da

Uploaded by

roshika.s2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views70 pages

Aa Eth Da

Uploaded by

roshika.s2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Understanding Greedy

Algorithms: Making Optimal


Choices
Exploring the Concept and Applications
contents

TOPIC: Greedy Algorithms


SHANKAR T(22MIC0129)
1. Coin Change Problem
2. Fractional Knapsack Problem
3. Huffman Coding
4. Activity Selection Problem
5. Shortest Path in Directed Acyclic Graph (DAG)
ROSHIKA S (22MIC0122)

6. Interval Scheduling Problem


7.Minimum Spanning Tree
8. Job Scheduling Problem
9. Gas Station Problem
10. Minimum Cost Spanning Tree
PRATHIBA R(22MIC0154)
11.Dijkstra's Algorithm
12. Prim's Algorithm
13. Subset Sum Problem
14. Change-making Problem
15. Watering Plants Problem
GOKULESH M (22MIC0102)
16. Elevator Problem
17. Meeting Rooms Problem
18. Maximum Units on a Truck
19. Non-overlapping Intervals
20. Buy Maximum Stocks with K Transactions
CODE /EXPLANATION GIVEN FOR

• COIN CHANGE PROBLEM


• WATERING PLANTS PROBLEM
• ELEVATOR PROBLEM
The Coin Change Problem is a classic algorithmic problem in which you're
asked to find the minimum number of coins needed to make a certain amount
of money. For example, if you have coins of denominations 1, 5, and 10, and
you want to make 12 cents, the minimum number of coins required would be
2 (one 10-cent coin and two 1-cent coins).

The Greedy Method is one approach to solving this problem. It involves


always choosing the largest denomination coin possible at each step until the
desired amount is reached. In the example above, using the Greedy Method,
you would start by selecting the largest coin less than or equal to the desired
amount, which is the 10-cent coin. Then you would repeat the process with
the remaining amount until you reach 12 cents.

However, the Greedy Method doesn't always provide the optimal solution for
the Coin Change Problem. There are scenarios where it fails to find the
minimum number of coins. For instance, if the coin denominations were 1, 3,
and 4, and you wanted to make 6 cents, the Greedy Method would choose
one 4-cent coin and two 1-cent coins, totaling 3 coins. But the optimal
solution would be to use two 3-cent coins, totaling only 2 coins. This
demonstrates that the Greedy Method doesn't always yield the best result for
the Coin Change Problem.
#include <stdio.h> printf("minimum number of coins
void findmincoins(int coins[], int numcoins, int needed:\n");
amount) {
int coincount[numcoins]; for (int i = 0; i < numcoins; i++) {
for (int i = 0; i < numcoins; i++) { if (coincount[i] > 0) {
coincount[i] = 0;
printf("%d coin(s) of denomination
}for (int i = numcoins - 1; i >= 0; i--) { %d\n", coincount[i], coins[i]); }
while (amount >= coins[i]) {
coincount[i]++;
} }
amount -= coins[i];
}}
int main() { int temp = coins[j];
int amount, numcoins; coins[j] = coins[j + 1];
printf("enter the amount: "); coins[j + 1] = temp;
scanf("%d", &amount); }
printf("enter the number of coins: "); }
scanf("%d", &numcoins; }
int coins[numcoins]; findmincoins(coins, numcoins, amount);
printf("enter the denominations of coins:\n");
for (int i = 0; i < numcoins; i++) { return 0;
scanf("%d", &coins[i]); }
}for (int i = 0; i < numcoins - 1; i++) {
for (int j = 0; j < numcoins - i - 1; j++) {
if (coins[j] < coins[j + 1]) {
Explanation
Function findMinCoins:
This function takes three arguments:
coins[]: An array containing the denominations of coins.
numCoins: The number of different denominations available.
amount: The total amount for which we need to find the minimum number of coins.
It initializes an array coinCount[] to store the count of each coin used, setting all counts to 0 initially.
Then, it iterates through the denominations of coins in reverse order (starting from the largest denomination).
It prompts the user to enter the amount and the number of denominations.
It then prompts the user to enter the denominations of coins one by one.
After that, it sorts the array of denominations in descending order. This step is crucial for the greedy approach used in the algorithm.
Finally, it calls the findMinCoins function to find and print the minimum number of coins needed for the given amount using the provided denominations.
output
WATERING PLANTS PROBLEM

• Initialize the current index i to 0 and the number of sprinklers turned on count to 0.
• While i is less than the length of the plants array:
• Find the rightmost position right that can be reached by turning on a sprinkler at the
current position i.
• If right is less than or equal to i, it means no sprinkler can cover the current plant at
position i, so return -1.
• Otherwise, increment the count of sprinklers turned on by 1.
• Set the current index i to right + 1, as all plants covered by the current sprinkler are
watered.
Example

• we have plants at positions [0, 1, 0, 0, 1, 0, 0, 0, 0, 0] and


• each sprinkler has a range of 2.

1.Start at index i = 0, count = 0.


• Rightmost reachable position from index 0 is 2 (positions 0, 1, 2 are covered).
• Increment count to 1.
• Move to index right + 1 = 3.
2. At index i = 3, count = 1.
• Rightmost reachable position from index 3 is 5 (positions 3, 4, 5 are covered).
• Increment count to 2.
• Move to index right + 1 = 6.
3 .At index i = 6, count = 2.
• Rightmost reachable position from index 6 is 8 (positions 6, 7, 8 are covered).
• Increment count to 3.
• Move to index right
4 .At index i = 9, count = 3.
• Rightmost reachable position from index 9 is 9 (position 9 is covered).
• Increment count to 4.
• No more plants left, exit loop.
• Return count, which is 4.
• So, the minimum number of sprinklers required to water all the plants is 4.
Code
#include <stdio.h> int main() {

int n, k;
// Function to find the minimum number of refills needed to water all plants
printf("Enter the number of plants: ");
int minRefills(int plants[], int n, int k) {
scanf("%d", &n);
int refills = 0;
int plants[n];
int i = 0;
printf("Enter the water requirements of each plant:\n");

for (int i = 0; i < n; i++) {


while (i < n) {
scanf("%d", &plants[i]);
int capacity = k;

while (i < n && plants[i] <= capacity) { }

capacity -= plants[i]; printf("Enter the watering can capacity: ");

i++; scanf("%d", &k);

int minRefillsNeeded = minRefills(plants, n, k);

if (i < n) { printf("Minimum number of refills needed: %d\n",


minRefillsNeeded);
refills++;

}
return 0;
}

return refills; }

}
output
Explanation
• Function minRefills:
• This function takes three arguments:
• plants[]: An array containing the water requirements of each plant.
• n: The number of plants.
• k: The capacity of the watering can.
• It initializes two variables:
• refills: The number of times the watering can needs to be refilled.
• i: An index used to traverse the array of plants.
• It enters a loop to iterate through the array of plants until all plants are watered:
• It refills the watering can to its maximum capacity.
• It then iterates through the plants, watering them one by one until either the watering can runs out of water or all reachable plants are watered.
• If not all plants are watered, it increments the refills counter to indicate that a refill is needed.
• Finally, it returns the total number of refills needed.
• main function:
• It prompts the user to input the number of plants, their water requirements, and the watering can's capacity.
• It calls the minRefills function with the provided inputs.
• It prints the minimum number of refills needed.
Elevator Problem
1.The elevator problem involves efficiently moving people between floors in a building
using an elevator system
2.The goal is to minimize wait times for passengers and maximize the throughput of
the elevator system
Problem Statement:
You have an elevator that can move between multiple floors in a
building. There are passengers waiting on different floors, each with
their own destination floor. Your task is to efficiently move these
passengers to their respective destinations while minimizing wait
times and optimizing the elevator's movement.
Input:
1.Number of floors in the building.
2.Initial position of the elevator.
3.List of passengers waiting on each floor, where each passenger is represented by
their current floor and destination floor.

Output:
Sequence of movements for the elevator, indicating which floor it
stops at and whether it picks up or drops off passengers at each stop.

Greedy Approach Solution:


• Initialization: Start with the elevator at a certain floor (usually the ground
floor) with no passengers.

• Decision Making: At each step, the elevator needs to decide which floor
to go to next. In a greedy approach, it would select the nearest floor
where there are waiting passengers or the nearest floor where there are
pending drop-offs.

• Update: After reaching a floor, pick up or drop off passengers as


necessary, then update the current state of the elevator (position,
passengers onboard, etc.).

• Repeat: Continue making decisions and updating the state until there are
no more passengers waiting or needing to be dropped off.
CODE
#include <stdio.h>
#include <stdlib.h>
int findNextFloor(int currentFloor, int* requests, int numRequests) {
int nextFloor = currentFloor;
int minDistance = 1000;
for (int i = 0; i < numRequests; i++) {
int distance = abs(currentFloor - requests[i]);
if (distance < minDistance) {
minDistance = distance;
nextFloor = requests[i];
}
}
return nextFloor;
}
• int main() {

• int numRequests;

• printf("Enter the number of floor requests: ");

• scanf("%d", &numRequests);

• int* requests = (int*)malloc(numRequests * sizeof(int));

• printf("Enter the floor requests: ");

• for (int i = 0; i < numRequests; i++) {

• scanf("%d", &requests[i]);

• }

• int currentFloor = 0;

• printf("Elevator movement:\n");

while (numRequests > 0) {

int nextFloor = findNextFloor(currentFloor, requests, numRequests);

printf("Elevator moving from floor %d to floor %d\n", currentFloor, nextFloor);

currentFloor = nextFloor;

for (int i = 0; i < numRequests; i++) {

if (requests[i] == nextFloor) {

for (int j = i; j < numRequests - 1; j++) {

requests[j] = requests[j + 1];

} numRequests--;

break; }

} }

free(requests);

return 0;}
Explanation
• This C program simulates the movement of an elevator based on floor requests. Let's break down the code:

• The findNextFloor function takes the current floor, an array of floor requests, and the number of requests. It iterates through the requests to find the nearest floor from
the current floor and returns it.
• In the main function:
• It prompts the user to enter the number of floor requests.
• Dynamically allocates memory for an array to store the requests.
• Reads the floor requests from the user.
• Initializes the current floor to 0.
• Enters a loop to process each request:
• Finds the next floor to move to using findNextFloor.
• Prints the movement of the elevator from the current floor to the next floor.
• Updates the current floor to the next floor.
• Removes the processed request from the array of requests and decrements the count of remaining requests.
• Frees the dynamically allocated memory.
• The program essentially simulates an elevator's movement by serving each floor request in the order that minimizes the distance traveled.
Definition of Greedy Algorithms
•Greedy algorithms make locally optimal
choices at each step with the hope of
finding a global optimum.
The Fractional Knapsack Problem is another classic optimization problem where you're
given a set of items, each with a weight and a value, and a knapsack with a maximum
weight capacity. The goal is to maximize the total value of items you can fit into the
knapsack without exceeding its weight capacity.

The Greedy Method can be applied to solve this problem efficiently. Here's how it
works:

1. Calculate the value-to-weight ratio for each item.


2. Sort the items in non-increasing order of their value-to-weight ratios.
3. Iterate through the sorted list of items and add items to the knapsack until it's full. If
an item can't be added entirely, add a fraction of it to maximize the total value.

Using the Greedy Method, you always select the item with the highest value-to-weight
ratio first, as it provides the best value for the available weight capacity. This approach
ensures that you're maximizing the total value of items in the knapsack.

However, unlike the Coin Change Problem, the Greedy Method does provide the
optimal solution for the Fractional Knapsack Problem.
Huffman coding is a method used for lossless data compression, particularly in encoding text
files. It's based on the concept of constructing a binary tree called a Huffman tree, where each
character or symbol is represented by a unique binary code.
1. Start with a set of symbols and their frequencies (how often each symbol appears in the data).
2. Create leaf nodes for each symbol, each with its frequency.
3. Repeat the following steps until there's only one node left (the root of the Huffman tree):
a. Select the two nodes with the lowest frequencies.
b. Combine them into a new internal node, whose frequency is the sum of the frequencies of the
two nodes.
c. Make the two selected nodes the left and right children of the new internal node.
4. The last remaining node is the root of the Huffman tree.

During this process, the Greedy Method is used to always select the two nodes with the lowest
frequencies at each step, ensuring that the resulting Huffman tree is optimal in terms of
minimizing the total encoding length.

After constructing the Huffman tree, each symbol can be encoded by traversing the tree from the
root to the corresponding leaf node, assigning a binary code based on the path taken. Symbols
with higher frequencies will have shorter binary codes, resulting in efficient compression.
EXAMPLE:
• Suppose we have an elevator with 10 floors and passengers waiting as follows:
• Floor 3: Passenger going to floor 7
• Floor 5: Passenger going to floor 2
• Floor 7: Passenger going to floor 1
• Floor 10: Passenger going to floor 4
• The elevator is at the ground floor. It sees that floors 3, 5, 7, and 8 have passengers. It decides to go to
the nearest floor with passengers, which is floor 3.
• The elevator picks up the passenger at floor 3 and updates its state.
• It then decides to go to floor 7 because it's the nearest floor with a passenger wanting to be dropped off.
• It drops off the passenger at floor 7 and updates its state.
• The elevator decides to go to floor 5 next because it's the nearest floor with waiting passengers.
• It repeats this process until all passengers are picked up or dropped off.
The Activity Selection Problem is a classic optimization problem where the goal is
to select the maximum number of activities that can be performed by a single
person or resource, given a set of activities with their start and finish times. The
objective is to maximize the number of activities without overlapping.

1. Sort activities: First, sort the activities based on their finish times in ascending
order. This step ensures that we always pick the activity that finishes earliest.

2. Select activities: Start with the first activity in the sorted list. Then, iteratively
select the next activity if its start time is greater than or equal to the finish time of
the previously selected activity.

3. Repeat: Continue this process until all activities are considered or until there are
no more activities that can be selected.

4. Output: The selected activities form the optimal solution to the problem.

The greedy approach works because at each step, it selects the locally optimal
choice (activity with earliest finish time) without considering future steps, yet this
In a Directed Acyclic Graph (DAG), there are no cycles, meaning there's always a well-
defined order of nodes. This property allows for efficient algorithms to find the shortest
path from a source node to all other nodes.

1. Topological Sorting: First, perform a topological sorting of the DAG. This sorting
arranges the vertices in such a way that for any directed edge from vertex u to vertex v,
vertex u comes before v in the ordering. This can be achieved using algorithms like Depth-
First Search (DFS) or Kahn's algorithm.

2. Greedy Approach: Once the topological ordering is obtained, initialize the shortest
distance array to infinity for all vertices except the source vertex, which is set to zero. Then,
iterate through each vertex in the topological order. For each vertex \(v\), consider all
outgoing edges from \(v\) and update the shortest distance to each adjacent vertex \(u\) if
the distance to \(u\) through \(v\) is shorter than the current shortest distance to \(u\).

3. Repeat: Continue this process until all vertices have been visited.

4. Output: After the process is complete, the shortest distance array will contain the shortest
distances from the source vertex to all other vertices in the DAG.
Interval Scheduling: Greedy Algorithms
Given a set R of n activity requests with start-finish times [si , fi ] for 1 ≤ i ≤ n, determine a subset of
R of maximum cardinality consisting of requests that are mutually non-conflicting.

Greedy template: Consider jobs in some order. Take each job provided it's compatible with the ones
already taken.

• [Earliest start time] Consider jobs in ascending order of start time sj.
• *[Earliest finish time] Consider jobs in ascending order of finish time fj.
• [Shortest interval] Consider jobs in ascending order of interval length fj - sj. (Repeatedly select
the activity with the smallest duration (fi−si), provided that it does not conflict with any
previously scheduled activities.)
• [Fewest conflicts] For each job, count the number of conflicting jobs cj. Schedule in ascending
order of conflicts cj.
Minimum Spanning Tree(MST)
• Let G=(V,E) be an undirected connected graph.
• A sub graph T=(V, E) of G is a spanning tree of G if
• T is a tree (i.e., it is acyclic)
• T covers all the vertices V
• contains |V| - 1 edges
• T has minimum total weight
• A single graph can have many different spanning trees.
KRUSKAL’S ALGORITHM
The Kruskal’s algorithm follows greedy approach. At every stage of the solution, it takes that edge which has
the minimum cost and builds the minimum spanning tree.

EXAMPLE: SOLUTION:
Job Scheduling Problem
Problem statement: Given an array of jobs where every job has a deadline and associated profit if
the job is finished before the deadline. It is also given that every job takes a single unit of time, so
the minimum possible deadline for any job is 1. How to maximize total profit if only one job can
be scheduled at a time.

Let’s break the question and try to find an approach for the same
•Given: array of jobs, array of deadline, array of profit
•Each job takes a unit time to complete
•A job can be completed on or before its deadline
•With every job completion, a profit will be earned
•We are asked to maximize the profit — which means it’s an optimization problem.

For optimization problems like this we generally use the GREEDY approach.
EXAMPLE:
EXAMPLE:
STEP 1:

Find the maximum deadline value,


dm, from the deadlines given.

STEP 2:

The output set of jobs scheduled within


the deadline are {J4, J3} with the
maximum profit of 140 (100+40=140).
The Gas Station Problem
Assume you have a road map, given as a graph with edge lengths, and the price
of gas at each location. Our car has a given tank capacity U. The objective is to
find a route from a starting point S to a target destination T that minimizes gas
costs.
Problem statement:
• Goal is to minimize the number of gas stops.
• Input: start & end positions, exact locations of all gas stations along the way. Exactly m miles
can be covered with one full tank of gas, irrespective of speed. Assume that initially gas tank
is full.
• Output: a list of gas stops.
• Greedy idea: Go as far as you can go before stopping for gas!

Greedy Approach:
• In this approach, we will visit each index once while selecting which index is the best
index to start the trip from.
• We know that a trip is possible only and only if the total gas of the trip is greater than or
equal to the total cost of the trip.
• We also know that we can go from one station to another only when gas[i] – cost[i] >= 0.
• This implies that the fuel can never be negative and we need to restart as soon as this
happens.
Example 1:
Input:
gas = [1, 2, 3, 4, 5]
cost = [3, 4, 5, 1, 2]
Output: 3
Explanation:
We will start the trip at index 3 and fill up with 4 units of gas. Total fuel = 0 + 4 = 4
Next go to index 4. Total fuel = 4 - 1 + 5 = 8
Next go to index 0. Total fuel = 8 - 2 + 1 = 7
Next go to index 1. Total fuel = 7 - 3 + 2 = 6
Next go to index 2. Total fuel = 6 - 4 + 3 = 5
Next, go to index 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index.
A greedy algorithm is an approach for solving a problem by selecting
the best option available at each step. It builds up a solution piece by
piece, always choosing the next piece that offers the most obvious
and immediate benefit. Greedy algorithms make locally optimal
choices with the hope of finding a global optimum.
DIJIKSTRA ‘S ALGORITHM

• Dijkstra’s algorithm is an algorithm for finding the shortest paths between nodes in a
weighted graph.
• Dijkstra’s algorithm follows a greedy approach by selecting the vertex with the
minimum distance from the source at each step
• . It makes locally optimal choices by continuously selecting the closest vertex and
updating the distances to the neighboring vertices.
Example
1)The vertex 0 is picked, include it in Set. So Set becomes {0}. After including 0 to Set,
update distance values of its adjacent vertices.
Adjacent vertices of 0 are 1 and 7.
The distance values of 1 and 7 are updated as 4 and 8.
2)Pick the vertex with minimum distance value and not already included in Set .The
vertex 1 is picked and added to Set.
So Set now becomes {0, 1}. Update the distance values of adjacent vertices of 1.
The distance value of vertex 2 becomes 12
3)Pick the vertex with minimum distance value and not already included in SPT .Vertex 7
is picked. So Set now becomes {0, 1, 7}.
Update the distance values of adjacent vertices of 7. The distance value of vertex 6 and
8 becomes finite (15 and 9 respectively).
4)Pick the vertex with minimum distance value and not already included in SPT (not in
SET). Vertex 6 is picked. So Set now becomes {0, 1, 7, 6}.
Update the distance values of adjacent vertices of 6. The distance value of vertex 5 and
8 are updated.
5)Repeat until all the vertices included from the given graph
Prims
algorithm-
example
PRIM’S ALGORITHM

• As a greedy algorithm, Prim’s algorithm will select the cheapest edge and mark
the vertex.
Method

• we will simply choose the edge with weight 1. In the next iteration we have
three options, edges with weight 2, 3 and 4.
• So, we will select the edge with weight 2 and mark the vertex. Now again we
have three options, edges with weight 3, 4 and 5.
• But we can’t choose edge with weight 3 as it is creating a cycle. So we will
select the edge with weight 4 and we end up with the minimum spanning tree
of total cost 7 ( = 1 + 2 +4).
SUBSET SUM PROBLEM

Given an array of integers


and a sum, the task is to select the largest
have all subsets of given numbers from the array the target sum or
array with sum equal to until you either reach
the given sum.

can no longer add


numbers without
exceeding the target sum.
Method

• given array [3, 4, 5, 2] target sum of 9

• Sort the array in descending order: [5, 4, 3, 2].


• Start with an empty subset and initialize the current sum to 0.
• Iterate through the sorted array.
• Add the current number to the subset if adding it won't exceed the target sum.
• If adding the current number would exceed the target sum, skip it.
• Repeat steps 4-5 until the target sum is reached or all elements have been
considered.
Example

• Start with an empty subset and current sum = 0.


• Add 5 to the subset. Current sum = 5.
• Add 4 to the subset. Current sum = 9. Target sum reached.

• Target sum 9 subset=[4,5]


Meeting Rooms Problem
1.The Meeting Rooms problem involves scheduling a series of meetings in a
set of available rooms, ensuring that none of the meetings overlap.
2.The goal is to efficiently assign meetings to rooms while minimizing the
number of rooms needed.

Problem Statement:
Given a list of meetings with their start and end times, determine the
minimum number of meeting rooms required to schedule all meetings
without any overlaps.
Greedy Approach Solution:
• Sort meetings by their start times: Begin by sorting all meetings based on their start times.
This allows us to process meetings in chronological order.

• Initialize: Start with an empty list of meeting rooms and a priority queue (min-heap) of
rooms sorted by their end times.

• Iterate through meetings: For each meeting in the sorted list:

• a. If the priority queue of rooms is empty (meaning all rooms are currently occupied),
allocate a new room for the meeting.

• b. Otherwise, check the end time of the earliest available room (the top of the priority
queue). If the meeting's start time is after or equal to this end time, assign the meeting to this
room and update its end time. If not, allocate a new room for the meeting.

• Repeat: Continue this process for all meetings.


EXAMPLE:
• Suppose we have the following meetings with their start and end times:
• Meeting 1: (1, 4)
• Meeting 2: (2, 5)
• Meeting 3: (5, 7)
• Meeting 4: (6, 8)
• Sort the meetings by their start times: [(1, 4), (2, 5), (5, 7), (6, 8)].
• Initialize an empty list of meeting rooms and a priority queue.
• Start processing meetings:
• a. For Meeting 1, allocate Room 1 (ending at time 4).
• b. For Meeting 2, allocate Room 2 (ending at time 5).
• c. For Meeting 3, Room 1 is available (end time 4), so allocate Room 1 (ending at time
7).
• d. For Meeting 4, Room 2 is available (end time 5), so allocate Room 2 (ending at time
8).
Maximum Units on a Truck
• The "Maximum Units on a Truck" problem involves loading items onto a
truck to maximize the total number of units that can be transported,
given the truck's maximum capacity.

Problem Statement:
Given a list of boxes, where each box contains a certain number of units
and has a certain number of available boxes, and the maximum capacity
of a truck, determine the maximum number of units that can be
transported on the truck.
Greedy Approach Solution:
• Sort boxes by their number of units: Begin by sorting all boxes based on the number of units
they contain. This allows us to prioritize loading boxes with the most units first.

• Iterate through sorted boxes: Starting with the box with the highest number of units, attempt
to load boxes onto the truck until the truck reaches its maximum capacity.

• Load boxes onto the truck: For each box in the sorted list:

• a. If adding the entire quantity of the current box to the truck does not exceed the truck's
remaining capacity, load the entire quantity onto the truck.

• b. If adding the entire quantity would exceed the truck's capacity, load only the maximum
amount of units that can fit, and then move to the next box.

• Repeat until the truck is full or there are no more boxes to load.
EXAMPLE:
• Suppose we have the following boxes with their respective units and quantities:
• Box 1: 10 units per box, 2 boxes available
• Box 2: 5 units per box, 8 boxes available
• Box 3: 8 units per box, 3 boxes available
• And the truck has a maximum capacity of 20 units.
• Sort the boxes by their units per box in descending order: Box 1 (10 units/box),
Box 3 (8 units/box), Box 2 (5 units/box).
• Initialize the total units loaded on the truck to 0.
• Start loading boxes onto the truck:
• a. Load all 2 boxes of Box 1 (20 units), reaching the truck's maximum capacity.
• b. Stop loading as the truck is full.
Non-overlapping Intervals

• The "Non-overlapping Intervals" problem involves finding the maximum


number of non-overlapping intervals from a given set of intervals.

Problem Statement:

Given a set of intervals on the real number line, find the maximum number
of non-overlapping intervals.
Greedy Approach Solution:
• Sort intervals by their end points: Begin by sorting all intervals based on their
end points in ascending order. This allows us to process intervals in a way that
maximizes the number of non-overlapping intervals.
• Initialize: Start with the first interval and keep track of the current end point.
• Count non-overlapping intervals: For each interval in the sorted list:
• a. If the start point of the current interval is greater than or equal to the current
end point, it means the current interval does not overlap with the previous one.
Increment the count of non-overlapping intervals and update the current end
point to the end point of the current interval.
• b. If the start point of the current interval is less than the current end point, it
means there is an overlap. Skip this interval and move to the next one.
• Repeat until the end of the list of intervals.
EXAMPLE:
• Suppose we have the following intervals:
• Interval 1: [1, 3]
• Interval 2: [2, 4]
• Interval 3: [5, 7]
• Interval 4: [6, 8]
• Sort the intervals by their end points: Interval 1 (end point: 3), Interval 2 (end point: 4), Interval
3 (end point: 7), Interval 4 (end point: 8).
• Initialize the count of non-overlapping intervals to 0 and the current end point to 0.
• Start iterating through the sorted intervals:
• a. Interval 1 starts at point 1, which is greater than the current end point (0). Increment the
count to 1 and update the current end point to 3.
• b. Interval 2 starts at point 2, which is less than the current end point (3). Skip this interval.
• c. Interval 3 starts at point 5, which is greater than the current end point (3). Increment the
count to 2 and update the current end point to 7.
• d. Interval 4 starts at point 6, which is less than the current end point (7). Skip this interval.
• Return the count of non-overlapping intervals, which is 2.

You might also like