题目:给你 k 种面值的钱,面值分别为 c1, c2 ... ck,再给一个总金额 n,问你最少需要多少张钱凑出这个金额,如果不可能凑出,则回答 -1 。
比如说,k = 3,面值分别为 1,2,5,总金额 n = 11,那么最少需要 3 枚张,即 11 = 5 + 5 + 1 。下面走流程。
思路:将k中面值,分别放入List集合中,并进行从大到小的排序,假设集合名字为coinList判断最大面值的钱是否比总金额n大。大于则将最大面值从集合总移除,第二大的面值的钱,作为集合中第一个元素。若小于n,则用n除以面值List集合集合中的第一个元素。得到一个int temp=n/coinList.get(0) 整数,将该面值coinList.get(0)和数量temp存到对象中,并存结果List集合。然后用n=n-(temp*coinList.get(0)),移除coinList.remove(0),然后按照此步骤循环下去。直到n=0;
实现代码如下
import java.util.List;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
public class ChangeMin {
public static void main(String[] args){
int n=106;
List<Integer> coinList=new ArrayList<Integer>();
List<Change> resList=new ArrayList<Change>();
coinList.add(1);
coinList.add(100);
coinList.add(5);
coinList.add(10);
coinList.add(20);
coinList.add(50);
List<Change> changeByList = getChangeByList(n,coinList,resList);
List<Integer> tableNames=changeByList.stream().map(Change::getAmount).collect(Collectors.toList());
int totalValue = changeByList.stream().mapToInt(Change::getAmount).sum();
JSONArray jsonArray = (JSONArray) JSONArray.toJSON(changeByList);
JSONObject jsonObject = new JSONObject();
LinkedHashMap<String, Object> linked = new LinkedHashMap<String,Object>();
linked.put("count", totalValue);
linked.put("result", jsonArray);
String jsonString = JSON.toJSONString(linked);
System.out.println(jsonString);
}
/**
* 凑零钱算法,给出指定的金额,用指定面额的纸币,用最少张数凑足零钱
* @param n
* @param coinList
* @return
*/
public static List<Change> getChangeByList(int n,List<Integer> coinList,List<Change> resList){
Collections.sort(coinList,Collections.reverseOrder());
if(n>0){
Change change = new Change();
if(coinList.size()>0){
Integer max = coinList.get(0);
int temp=0,result=0;
List<Integer> tempList=new ArrayList<Integer>();
if(n<max){
coinList.remove(0);
result=n;
}else{
temp=n/max;
result=n-(temp*max);
change.setChange(max);
change.setAmount(temp);
resList.add(change);
}
getChangeByList(result,coinList,resList);
}
}
return resList;
}
}
@Data
class Change{
private int change;
private int amount;
}