凑零钱算法,给出一整数,用给定的面值的钱,拼凑成该整数

题目:给你 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值