Greedy algorithm to solve coin change problem

Source: Internet
Author: User

If there is a currency, it has 1 cents, 2 points, 5 points and 1 corners of the coin, at least how many coins to find the K-penny change?

According to the idea of greedy algorithm, it is necessary to use the coin with the most face value constantly. If the value of change is less than the maximum coin value, try the second largest coin, and so on.

The code is as follows:

#include <iostream>using namespace std; #define One 1#define, 2#define FIVE 5#define TEN 10int Main () {    int mon EY;    int one=0,two=0,five=0,ten=0;    cout<< "Enter the money for change (to be divided into units):";    cin>>money;        Try each kind of coin    while (Money>=ten)    {        ten++;        Money-=ten;    }    while (money>=five)    {        five++;        money-=five;    }    while (Money>=two)    {        two++;        money-=two;    }    while (Money>=one)    {        one++;        Money-=one;    }        Output    cout<< "1 Corner coin Count:" <<ten<<endl;    cout<< "5 cent coin Count:" <<five<<endl;    cout<< "2 cent coin Count:" <<two<<endl;    cout<< "1 cent coin Count:" <<one<<endl;        return 0;}

Although the greedy algorithm is not able to get the overall optimal solution for all problems, many problems in practical application can be obtained by using greedy algorithm to obtain the optimal solution. Sometimes the optimal solution of the problem can not be obtained even though the greedy algorithm is used, but the final result is also a better solution

Greedy algorithm to solve coin change problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.