The basic idea of the greedy algorithm is to gradually approach the given goal from an initial solution of the problem, so as to obtain a better solution as much as possible. get an approximate solution.
- there is no guarantee that the final interpretation is optimal;
- problems that cannot be used to find maximum or minimum solutions;
-Only the range of feasible solutions that satisfy certain constraints can be obtained.
Example: changing change
Java code description
public class Test { static int MAXN = 9; static int[] parvalue = {10000,5000,1000,500,200,100,50,20,10}; static int[] num = new int[9]; public static void main(String[] args) { int i; float m; System.out.println("Please enter the amount to be processed"); Scanner sc = new Scanner(System.in); m = sc.nextFloat(); exchange((int)(100*m)); System.out.println("Change group is"); for(i=0;i<MAXN;i++){ if(num[i]>0){ System.out.println((float)(parvalue[i]/100.0)+"元 "+num[i]+"张"); } } } public static void exchange(int n){ int i; for(i = 0;i<MAXN;i++){ if(n>parvalue[i]){ //find the maximum denomination break; } } while(n>0&&i<MAXN){ //Loop to find progressively smaller denominations if(n>=parvalue[i]){ n-=parvalue[i]; //Get the one with the largest denomination num[i]++; //Add one to the current denomination counter }else if(n<10&&n>=5){ num[MAXN-1]++; break; }else{ i++; } } } }
operation result: