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;
}
}