145
The knapsack problem
Your knapsack can hold 35 pounds of items. The stereo system is
the most expensive, so you steal that. Now you don’t
have space for
anything else.
You got $3,000 worth of goods. But wait! If you’d picked the laptop and
the guitar instead, you could have had $3,500 worth of loot!
Clearly, the greedy strategy doesn’t give you the optimal solution here.
But it gets you pretty close. In the next chapter, I’ll
explain how to
calculate the correct solution. But if you’re a thief in a shopping center,
you don’t care about perfect. “Pretty good” is good enough.
Here’s the takeaway from this second example: sometimes, perfect is the
enemy of good. Sometimes all you need is an
algorithm that solves the
problem pretty well. And that’s where greedy algorithms shine, because
they’re simple to write and usually get pretty close.
Dostları ilə paylaş: