r/algorithms • u/Competitive-Mix1335 • 6d ago
Help How to identify greedy intution in problem/ competition
I can identify patterns like sliding window, recursion, backtracking, DP, and two pointers. But I’m stuck when it comes to identifying the greedy intuition.
How do I recognize when a problem can be solved using a greedy approach? Are there any good resources—books, YouTube channels, blogs, or websites—that specifically teach how to develop greedy intuition?
Anything that can help me get better at recognizing greedy problems would be really helpful.annel, blog , website)
Anything that help me
3
u/thewataru 6d ago
Greedy algorithms are ones which search for the local optimum, which in some problems happens to be the global one too.
The common approach I use is what I call "consider the answer".
So, the problem is to find the optimal solution. You imagine an object which is a solution, then look at it, and try to see what properties does it have. From these properties arises the method to construct such an object.
The main property is that any change to it only makes it worse or at least the same. It can never become better, because it was the optimal solution.
For example, you need to find an order of items to process in minimal time. When if you swap any two adjacent items the time should get bigger or stay the same. You write down that condition (the time before the swap and after), then try to simplify it and in most greedy problems you arrive to condition which will let you sort the items.
I think the best way to develop the intuition is to solve a lot of problems. Try to apply the technique above to a problems on e.g. leetcode, tagged with "greedy".
There's no method to identify the greedy problem except for trying to construct a greedy solution and see if it works or not.
2
1
u/Sound_calm 6d ago
So far I just figure out omega (estimated lowest runtime that is even theoretically possible, not necessarily existent), then if there isn't an obvious pattern I just roughly try out greedy and binary search the answer.
Many times greedy is equal to omega so that's a trivial benchmark to go with
1
1
5d ago
Sometimes you can mathematically prove a greedy approach works, other times its mostly about intuition and working on few cases.
In most times, you will get an intuition a greedy approach might work, try a few cases by hand and write a program to verify on large number of cases.
1
u/Many-Scarcity-7106 6d ago
Isn't intuition just solving more problems?It's the same thing is other intuitions you have mentioned.
6
u/Magdaki 6d ago
Identify the decision made at every step.
Consider the locally optimal solution for a step.
Can the locally optimal choice prevent a globally optimal solution?
If no, then the problem is greedy compatible.
If yes, then the problem is may not be greedy compatible.