编辑代码

// 定义水果列表
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);