Greedy Algorithm
An algorithm used to recursively construct a set of objects from the smallest possible constituent parts.
Given a set of ๐ k
integers (๐ a_1
, ๐ a_2
, ..., ๐ a_k
) with ๐ a_1<a_2<...<a_k
, a greedy algorithm can be used to
find a vector of coefficients (๐ c_1
, ๐ c_2
, ..., ๐ c_k
) such that
where ๐ cยทa
is the dot product, for some given integer ๐ n
. This can be accomplished by letting
๐ c_i=0
for ๐ i=1
, ..., ๐ k-1
and setting
where ๐ |_x_|
is the floor function. Now define the difference between the representation and ๐ n
as
If ๐ Delta=0
at any step, a representation has been found. Otherwise, decrement the nonzero ๐ c_i
term with least ๐ i
, set all ๐ c_j=0
for ๐ j<i
, and build up the remaining terms from
for ๐ j=i-1
,
..., 1 until ๐ Delta=0
or all possibilities have been exhausted.
For example, McNugget numbers are numbers which are representable using only ๐ (a_1,a_2,a_3)=(6,9,20)
. Taking ๐ n=62
and applying the algorithm iteratively gives the sequence
(0, 0, 3), (0, 2, 2), (2, 1, 2), (3, 0, 2), (1, 4, 1), at which point ๐ Delta=0
. 62 is therefore a McNugget
number with
If any 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 an arbitrary fraction into an Egyptian fraction in a finite number of steps.
For a fraction ๐ a/b
, 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. Then find the least
integer ๐ x_2
such that ๐ 1/x_2<=a/b-1/x_1
. Iterate until there is no remainder. 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, Integer Relation, Knapsack Problem, Levine-O'Sullivan Greedy Algorithm, McNugget Number, Reverse Greedy Algorithm, Square Number, Subset Sum Problem, Sylvester's SequenceExplore with Wolfram|Alpha
More things to try:
References
๐ ImageWagon, S. "Greedy Coins." http://library.wolfram.com/infocenter/MathSource/5187/.
Referenced on Wolfram|Alpha
Greedy AlgorithmCite this as:
Weisstein, Eric W. "Greedy Algorithm." From MathWorld--A Wolfram Resource. https://mathworld.wolfram.com/GreedyAlgorithm.html
