TOPICS
Search

Greedy Algorithm


A greedy algorithm is an algorithm that makes a locally best feasible choice at each step without backtracking. Such choices need not give a globally optimal result.

For a set of k positive integers (a_1, a_2, ..., a_k) with a_1<a_2<...<a_k, a greedy coin algorithm starts with the largest denomination and works downward. One seeks a vector of nonnegative integer coefficients (c_1, c_2, ..., c_k) such that

 sum_(i=1)^kc_ia_i=c·a=n,
(1)

where c·a is the dot product, for a given nonnegative integer n. Initially let all c_i=0 and set

 c_k=|_n/(a_k)_|,
(2)

where |_x_| is the floor function. Now define the difference between the representation and n as

 Delta=n-c·a.
(3)

The greedy procedure continues by setting

 c_j=|_Delta/(a_j)_|
(4)

for j=k-1, ..., 1, recomputing Delta after each assignment. If Delta=0, a representation has been found; otherwise the greedy procedure fails, even if a representation exists.

A separate backtracking search can find a representation by decrementing the nonzero c_i with least i, resetting all c_j=0 for j<i, recomputing Delta, and greedily filling those lower-denomination coefficients in descending order, recomputing Delta after each assignment. Repeating this process finds a representation or exhausts the finite search space. This extension is a backtracking algorithm.

For example, McNugget numbers are numbers which are representable using only (a_1,a_2,a_3)=(6,9,20). For n=62, the greedy procedure gives (0,0,3) with remainder 2 and fails. Backtracking finds (1,4,1), so 62 is a McNugget number with

 62=(1·6)+(4·9)+(1·20).
(5)

If every positive integer n can be represented with c_i=0 or 1 using a sequence (a_1, a_2, ...), then this sequence is called a complete sequence.

A greedy algorithm can also be used to break down a fraction a/b, with positive integers 0<a<b, into an Egyptian fraction in a finite number of steps. Find the least integer x_1 such that 1/x_1<=a/b, i.e.,

 x_1=[b/a],
(6)

where [x] is the ceiling function. If the remainder is positive, find the least integer x_2 such that 1/x_2<=a/b-1/x_1. Iterate until there is no remainder. For n>=5, the algorithm gives two or fewer terms for 1/n and 2/n, three or fewer terms for 3/n, and four or fewer for 4/n.


See also

Coin Problem, Complete Sequence, Egyptian Fraction, Frobenius Equation, Frobenius Number, Greedy Matching, Integer Relation, Knapsack Problem, Levine-O'Sullivan Greedy Algorithm, McNugget Number, Nearest Neighbor Algorithm, Reverse Greedy Algorithm, Square Number, Subset Sum Problem, Sylvester's Sequence

Explore with Wolfram|Alpha

References

Wagon, S. "Greedy Coins." https://library.wolfram.com/infocenter/MathSource/5187/.

Referenced on Wolfram|Alpha

Greedy Algorithm

Cite this as:

Weisstein, Eric W. "Greedy Algorithm." From MathWorld--A Wolfram Resource. https://mathworld.wolfram.com/GreedyAlgorithm.html

Subject classifications