import java.util.Arrays;
import java.util.Comparator;
public class GreedyBeanBag {
static class Bean {
int weight;
int value;
public Bean(int weight, int value) {
this.weight = weight;
this.value = value;
}
}
public static double getMaxValue(Bean[] beans, int capacity) {
Arrays.sort(beans, Comparator.comparingDouble(b -> (double) b.value / b.weight));
double totalValue = 0;
for (Bean bean : beans) {
if (capacity >= bean.weight) {
totalValue += bean.value;
capacity -= bean.weight;
} else {
double fraction = (double) capacity / bean.weight;
totalValue += fraction * bean.value;
break;
}
}
return totalValue;
}
public static void main(String[] args) {
Bean[] beans = {new Bean(5, 10), new Bean(3, 8), new Bean(2, 5)};
int capacity = 10;
double result = getMaxValue(beans, capacity);
System.out.println("结果为: " + result);
}
}