0% found this document useful (0 votes)
11 views7 pages

Lec 4

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)
11 views7 pages

Lec 4

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/ 7

Lec-4

Greedy and Maths


"A greedy algo is any algo that follows the problem-solving heuristic of making the
locally optimal choice at each stage."

Adv.
● Easier to describe and code up .
● Often be implemented more efficiently than other algorithms.

Drawbacks-
● Designing greedy algorithms can be easy,finding the right approach can be hard.
● Showing a greedy algorithm is correct often requires a nuanced argument.
Greedy Problems
https://leetcode.com/problems/stone-game/description/

https://codeforces.com/problemset/problem/276/C

https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/description/

https://www.geeksforgeeks.org/optimal-strategy-for-a-game-dp-31/
Fractional Knapsack
Q. Given weights and values of N items, we need to put these items in a knapsack of
capacity W to get the maximum total value in the knapsack.
Note: you are allowed to break the item.

Algo:-

Calculate Ratios: Compute the value-to-weight ratio for each item.


Sort Items: Sort items in descending order of their value-to-weight ratio.
Pick Full Items: Iterate through the sorted items, adding their value if their weight fits
within the current capacity.
Pick Fractional Item: If an item's weight exceeds the remaining capacity, take the
fraction that fits and add its value.
Return Profit: Stop when the knapsack is full and return the total profit.
N = 3, W = 50, values[] = {100,60,120}, weight[] = {20,10,30}.

Initially capacity of bag(W) = 50, value = 0


Item 1 has a weight of 10, we can pick it up.
Current weight = 50 - 10 = 40 ,Current value = 60.00
Item 2 has a weight of 20 , we can pick it up.
Current weight = 40 - 20 = 20 ,Current value = 60.00 + 100.00 = 160.00
Item 3 has a weight of 30 , but current knapsack capacity is 20.Only a fraction of it is
chosen.
Current weight = 20 - 20 = 0 ,Final value = 160.00 + (120/30 )*20 = 240.00
Activity Selection Algo
the job or activity of planning the times at which particular tasks will be done or
events will happen.

Problems
https://www.geeksforgeeks.org/problems/n-meetings-in-one-room-1587115620/1

https://leetcode.com/problems/merge-intervals/description/

https://leetcode.com/problems/maximum-earnings-from-taxi/description/

You might also like