贪心算法c语言纸币,贪心算法——找纸币问题

package greed;

import java.util.Arrays;

/**

* 找钱问题

* User: luoweifu

* Date: 14-1-14

* Time: 下午8:08

*/

public class GiveChange {

public static int gaiveChange(MoneyBox[] moneyBoxes, int target) {

Arrays.sort(moneyBoxes);

int count = 0;

for(int i = moneyBoxes.length-1; i >= 0; i--) {

int currentCount = Math.min(moneyBoxes[i].getCount(), target/moneyBoxes[i].getValue());

target -= currentCount*moneyBoxes[i].getValue();

count += currentCount;

}

if(target > 0) {

count = -1;

}

return count;

}

public static void main(String args[]) {

MoneyBox[] moneyBoxes = {

new MoneyBox(1, 3),

new MoneyBox(2, 0),

new MoneyBox(5, 2),

new MoneyBox(10, 1),

new MoneyBox(20, 0),

new MoneyBox(50, 3),

new MoneyBox(100, 5),

};

int result = gaiveChange(moneyBoxes, 620);

if(result > 0)

System.out.println(result);

else

System.out.println("No");

}

}

/**

* 钱盒子

*/

class MoneyBox implements Comparable{

private int value;

private int count;

MoneyBox(int value, int count) {

this.value = value;

this.count = count;

}

int getValue() {

return value;

}

void setValue(int value) {

this.value = value;

}

int getCount() {

return count;

}

void setCount(int count) {

this.count = count;

}

@Override

public int compareTo(Object o) {

MoneyBox moneyBox = (MoneyBox)o;

if(this.value < moneyBox.getValue())

return -1;

else if(this.value == moneyBox.getValue())

return 0;

else

return 1;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值