algorithm
TYChan6028
>Consider the problem of making change for cents using the fewest number of coins. Assume that each coin’s value is an integer.
In order to prove our solution optimal, we have to show that our solution satisfies the greedy-choice property and exhibits optimal substructure.
The first key ingredient is the greedy-choice property: we can assemble a globally optimal solution by making locally optimal (greedy) choices. – textbook, p.424
Consider the optimal way to change (): The greedy choice takes coin .
Say does not include , then must only consist of coins . This means that coins must add up to .
k | Constraints | Max. value of in any | |
---|---|---|---|
1 | 1 | ||
2 | 5 | ||
3 | 10 | ||
4 | 25 |
As we can see from the chart, , which shows that no optimal solution exists under this assumption.
Therefore, coin is indeed the greedy choice to make. This reduces the problem to coin-changing cents, which can again be optimally solved using the greedy-choice property.
A problem exhibits optimal substructure if an optimal solution to the problem contains within it optimal solutions to subproblems. – textbook, p.425
Let be the minimum number of coins needed to coin-change cents.
Suppose is an optimal solution to , then:
⟹
Therefore, by substituting , the cashier's algorithm exhibits optimal substructure.
Let be such that and the greedy algorithm returns where is a solution. Let be an optimal solution for .
Basis step
If , then and .
Inductive step
Assume for , then .
According to our conjecture, must also contain a .
Suppose does not contain , then .
If any , . This would violate the optimality of since number of coins could be traded for a single coin.
A contradiction is reached. Thus must contain a .
We showed that making the greedy choice at every iteration leads to the optimal solution . This proves the greedy-choice property.
To prove that the greedy algorithm exhibits optimal substructure, we let and let be an optimal solution.
We assume that is an optimal solution for . If it were not, then for an optimal solution . This means , which is a contradiction since is an optimal solution.
Thus, is an optimal solution for . This proves the optimal substructure property.
sort
: while
loop: for
loop: