A thief robs a store and finds n items, with item i being worth $Vi and having weight Wi pounds. The thief can carry at most W∈ N in his knapsack but he wants to take as valuable a load as possible. Which item should he take?
Fractional knapsack
The setup is same as 0-1 knapsack, but the thief can take fractions of items
Optimal Substructure
Both knapsack problems exhibit the optimal substructure property:
For 0-1 knapsack problem, if we remove item j from this load, the remaining load must be at most valuable items weighing at most W-wj from n-1 items.
For fractional one, if we remove a weight w of one item j from the optimal load, then the remaining load must be the most valuable load weighing at most W-w that the thief can take from the n-1 original items plus wj-w pounds of item j
Example
There are 5 items that have a value and weight list below, the knapsack can contain at most 100 Lbs. Solve the problem both as fractional knapsack and 0/1 knapsack.
// fractional knapsack func _knapsack(values, weights []int, capfloat64)float64 { n := len(values) var items Items for i := 0; i < n; i++ { items = append(items, Item{float64(values[i]), float64(weights[i])}) } sort.Sort(items)
var ans float64 for _, item := range items { ifcap >= item.weight { ans += item.value cap -= item.weight } else { ans += (item.value / item.weight) * cap break } } return ans }