AsLegend's blog

By AsLegend, history, 10 months ago, In English

How to Know If a Problem Can Be Solved Greedily? Let's Demystify It!

Have you ever stared at a problem and wondered: "Is greedy enough here? Or do I need DP?" You’re not alone. Recognizing when a greedy algorithm works is one of the most powerful skills a competitive programmer can develop.

Let’s break it down.

What is a Greedy Algorithm?

A greedy algorithm builds a solution step by step, always picking what seems best at the moment, hoping it leads to the global optimum.

How to Detect Greedy Applicability?

Here are some tell-tale signs that greedy might be the right fit:

  1. You can sort the data → If sorting helps you make decisions, there's a good chance it's greedy.
  2. Making a local optimal choice leads to a global solution → Classic example: Activity Selection, Huffman Encoding, Fractional Knapsack.
  3. The problem wants “minimum number of…” or “maximum value of…” → These often favor greedy strategies.
  4. Choices are independent of the future once made → If what you do now doesn’t affect future choices, greediness might work.
  5. DP solution gives TLE, Greedy is needed for speed → Try proving the greedy choice using an exchange argument (more on that below).

Practice Problems

Full text and comments »

  • Vote: I like it
  • -21
  • Vote: I do not like it

By AsLegend, history, 17 months ago, In English

// syntax for inserting elements in set using iterator range

s.insert(v.begin(), v.end());

for (int x : s) {
    cout << x << " ";
}
// Output: 10 20 30

return 0;

}

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

By AsLegend, history, 22 months ago, In English

Yesterday, I participated in a real contest in my life, in July 11, 2024. Codeforces contests are very great, and fair also. I struggled a bit at first the time I'm new with this platform. After a while, I've been familiar with all the things in it. I hope more contests from Codeforces team, then I can boost my rating. Right now, I'm just a newbie.

Full text and comments »

  • Vote: I like it
  • +4
  • Vote: I do not like it