开发者

What is the Best Complexity of a Greedy Algorithm?

开发者 https://www.devze.com 2023-04-12 01:10 出处:网络
It seems like the best complexity would be linear O(n). Doesn\'t matter the case really, I\'m speaking of greedy algorithms in general.

It seems like the best complexity would be linear O(n).

Doesn't matter the case really, I'm speaking of greedy algorithms in general.

Sometimes it pays off to be greedy?

In the specific case that I am interested would be computing change.

Say you need to give 35 cents in change. You have coins of 1, 5, 10, 25. The greedy algorithm, coded simply, would solve this problem quickly and ea开发者_如何学运维sily. First grabbing 25 cents the highest value going in 35 and then next 10 cents to complete the total. This would be best case. Of course there are bad cases and cases where this greedy algorithm would have issues. I'm talking best case complexity for determining this type of problem.


Any algorithm that has an output of n items that must be taken individually has at best O(n) time complexity; greedy algorithms are no exception. A more natural greedy version of e.g. a knapsack problem converts something that is NP-complete into something that is O(n^2)--you try all items, pick the one that leaves the least free space remaining; then try all the remaining ones, pick the best again; and so on. Each step is O(n). But the complexity can be anything--it depends on how hard it is to be greedy. (For example, a greedy clustering algorithm like hierarchical agglomerative clustering has individual steps that are O(n^2) to evaluate (at least naively) and requires O(n) of these steps.)


When you're talking about greedy algorithms, typically you're talking about the correctness of the algorithm rather than the time complexity, especially for problems such as change making.

Greedy heuristics are used because they're simple. This means easy implementations for easy problems, and reasonable approximations for hard problems. In the latter case you'll find time complexities that are better than guaranteed correct algorithms. In the former case, you can't hope for better than optimal time complexity.


GREEDY APPROACH

  1. knapsack problem...sort the given element using merge sort ..(nlogn)
  2. find max deadline that will take O(n)
  3. using linear search select one by one element....O(n²)

nlogn + n + n² = n² in worst case....

now can we apply binary search instead of linear search.....?


Greedy or not has essentially nothing to do with computational complexity, other than the fact that greedy algorithms tend to be simpler than other algorithms to solve the same problem, and hence they tend to have lower complexity.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号