You are on page 1of 9

Greedy Algorithms

- Srivaths P
Social Media Profiles: sriv.bio.link
Goal
• To learn about greedy algorithms.

• Go through problems where greedy would and


would not work.

• Differentiate between greedy and dynamic


programming.

• Solve problems related to greedy algorithms.


What are Greedy Algorithms?
Greedy algorithms select the best option
available immediately.

It does not worry whether the current best


option is the optimal option in the future.

Greedy algorithms are generally related to


searching and sorting.
Where greedy works
Greedy algorithms work when at every step, there
is a choice that is optimal for the problem up to
that step.

• Take the subset of an array with ANY integer in it.


Maximize the sum of the subset.

• Kadane’s Algorithm for the maximum subarray


sum of an array.
Where greedy does not work
• Coin change problem: Given N coins with different
values, use the minimum number of coins to add up
to a value K.

• 0-1 Knapsack Problem: Given weights and profit of N


values, move them into a bag which can hold upto
weight W. Maximize profit.

NOTE: You can only take an item, or exclude an item.


More greedy examples
• Fractional Knapsack Problem: Given weights and
profit of N values, move them into a bag which
can hold upto weight W. Maximize the profit of
the items in the bag.

• If we have N events, and the starting and ending


times of each event, maximize the number of
events that can be attended.
Greedy vs Dynamic Programming
Greedy and DP are almost polar opposites.

Greedy only considers the local maximum. It doesn’t


consider the global maximum.

Dynamic programming finds the globally best solution


unlike greedy.

Generally, greedy is faster than DP due to not having to


consider a lot of cases.
Problem Solving
• https://leetcode.com/problems/non-overlapping-intervals/

• https://codeforces.com/problemset/problem/1791/D

• https://codeforces.com/problemset/problem/1791/G1

• https://codeforces.com/problemset/problem/1791/E

• https://codeforces.com/problemset/problem/1744/D
Thanks for watching!

You might also like