You are given a set of bars of gold and your goal is to take as much gold as possible into your bag. There is just one copy of each bar and for each bar you can either take it or not (hence you cannot take a fraction of a bar).
Given π gold bars, find the maximum weight of gold that fits into a bag of capacity π.
The first line of the input contains the capacity π of a knapsack and the number π of bars of gold. The next line contains π integers π€0,π€1, . . . ,π€πβ1 defining the weights of the bars of gold.
1 β€ π β€ 104; 1 β€ π β€ 300; 0 β€ π€0, . . . ,π€πβ1 β€ 105.
Output the maximum weight of gold that fits into a knapsack of capacity π.
capacity_and_number = gets.chomp.split
bars_str = gets.chomp.split
capacity = capacity_and_number[0].to_i
number = capacity_and_number[1].to_i
bars = bars_str.map{|e| e.to_i}
previous_iteration = []
results = {}
bars.each do |bar|
for weight in 0..capacity do
previous_result = results[weight]
if bar <= weight
previous_max = previous_iteration.last[weight - bar] unless previous_iteration.empty?
if previous_result
if previous_max + bar <= previous_result
results[weight] = previous_result
elsif previous_max + bar <= weight
results[weight] = previous_max + bar
elsif previous_max + bar >= weight
results[weight] = previous_result
end
else
results[weight] = bar
end
else
results[weight] = previous_result ? previous_result : 0
end
end
previous_iteration << results.dup
end
puts results.values.max