0
$\begingroup$

Link to leetcode problem: https://leetcode.com/problems/container-with-most-water/?envType=study-plan-v2&envId=top-interview-150

if we consider this solution: https://leetcode.com/problems/container-with-most-water/solutions/5022358/video-two-pointer-solution/

I'm kind of confused why this specific two-pointer solution is also considered a greedy approach because I thought for greedy approaches, we have to find the optimal solution locally 'so that it never goes back and reverses direction', but in the solution, we always have to compare with our previous area.

Any tips on how to intuitively know that we should use greedy (as opposed to DP for example) for this problem as well because in general greedy may not work for all optimization problems?

$\endgroup$

1 Answer 1

0
$\begingroup$

There is in general no way to know in advance whether a greedy algorithm will work, other than trying it. My experience is that a typical approach is to try the obvious greedy algorithms first, and see if any of them work. If any of them work, great, you're done! If not, then you have to apply more sophisticated methods (such as dynamic programming).

I find random testing a powerful way to quickly try out a possible greedy approach. See How to prove greedy algorithm is correct.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.