const fruits = [
{ name: '苹果', weight: 15, value: 300 },
{ name: '香蕉', weight: 18, value: 180 },
{ name: '橘子', weight: 10, value: 150 },
{ name: '猕猴桃', weight: 9, value: 270 }
];
const maxWeight = 20;
fruits.sort((a, b) => b.value / b.weight - a.value / a.weight);
const strategy = [];
let totalWeight = 0;
let totalValue = 0;
for (let i = 0; i < fruits.length; i++) {
const fruit = fruits[i];
if (totalWeight + fruit.weight <= maxWeight) {
strategy.push(fruit.name);
totalWeight += fruit.weight;
totalValue += fruit.value;
}
}
console.log('装水果的策略:', strategy.join(', '));
console.log('背包中水果的总重量:', totalWeight);
console.log('背包中水果的总价值:', totalValue);