package lihkg_problem_package;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Lihkg_Problem {
public static void main(String[] args) {
List<Jewelry> _list = new ArrayList<>();
_list.add(new Jewelry(163, 12));
_list.add(new Jewelry(221, 31));
_list.add(new Jewelry(124, 5));
_list.add(new Jewelry(582, 20));
_list.add(new Jewelry(631, 30));
_list.add(new Jewelry(198, 7));
_list.add(new Jewelry(317, 20));
_list = _list.stream().sorted(Comparator.comparing(Jewelry::get_cost_effective).reversed())
.collect(Collectors.toList());
for (int i = 1; i < 101; i++) {
System.out.println("n = " + i + " ,price = " + most_value(_list, i));
}
}
private static double most_value(List<Jewelry> _list, double n) {
if (_list.size() == 0 || _list.stream().min(Comparator.comparing(e -> e.weight)).get().weight > n) {
return 0;
}
List<Jewelry> _list_new = _list.stream().filter(e -> e.weight <= n).collect(Collectors.toList());
double global_solution = 0;
for (Jewelry item : _list_new) {
double solution =
item.price + most_value(_list_new.stream().filter(e -> e != item).collect(Collectors.toList()),
n - item.weight);
global_solution = Math.max(global_solution, solution);
}
return global_solution;
}
}
class Jewelry {
public final double price;
public final double weight;
public final double cost_effective;
public Jewelry(double price, double weight) {
this.price = price;
this.weight = weight;
this.cost_effective = price / weight;
}
public Double get_cost_effective() {
return cost_effective;
}
}
同上面個solution一樣answer,不過計埋性價比好似好無謂