What if you could carry the most valuable parts of your items instead of all or nothing?
Why Fractional Knapsack Problem in DSA Go?
Imagine you have a backpack with limited weight capacity, and you want to fill it with items to get the most value. You try to pick whole items one by one, but some items are too heavy or you can't carry them all.
Picking whole items manually is slow and often leaves unused space. You might miss out on better combinations or forget to consider taking parts of items, leading to less total value.
The Fractional Knapsack Problem lets you take fractions of items, not just whole ones. This way, you fill your backpack optimally by choosing the most valuable parts first, maximizing total value easily.
items := []Item{{weight: 10, value: 60}, {weight: 20, value: 100}}
// Try to pick whole items only
for _, item := range items {
if capacity >= item.weight {
capacity -= item.weight
totalValue += item.value
}
}items := []Item{{weight: 10, value: 60}, {weight: 20, value: 100}}
sort.Slice(items, func(i, j int) bool {
return float64(items[i].value)/float64(items[i].weight) > float64(items[j].value)/float64(items[j].weight)
})
for _, item := range items {
if capacity >= item.weight {
capacity -= item.weight
totalValue += item.value
} else {
fraction := float64(capacity) / float64(item.weight)
totalValue += float64(item.value) * fraction
break
}
}This concept enables you to maximize the total value you carry by smartly choosing whole or fractional parts of items within your weight limit.
Imagine packing a suitcase for a trip where you can only carry a certain weight. Instead of taking whole bulky items, you can take parts of things like food or liquids to get the most benefit without exceeding the limit.
Manual picking of whole items wastes space and value.
Fractional Knapsack allows taking parts of items for maximum value.
Sorting items by value-to-weight ratio is key to the solution.
Practice
Fractional Knapsack Problem?Solution
Step 1: Understand the problem goal
The fractional knapsack problem allows taking parts of items to maximize total value without exceeding weight capacity.Step 2: Identify the correct objective
The goal is to maximize value by possibly taking fractions, not just whole items or minimizing weight.Final Answer:
Maximize the total value by taking fractions of items within the weight limit -> Option DQuick Check:
Goal = Maximize value with fractions [OK]
- Thinking only whole items can be taken
- Confusing weight limit with item count limit
- Assuming minimizing weight is the goal
Solution
Step 1: Identify sorting criteria for fractional knapsack
Items must be sorted by value-to-weight ratio in descending order to pick the best value per weight first.Step 2: Check each option's sorting logic
sort.Slice(items, func(i, j int) bool { return items[i].value/items[i].weight > items[j].value/items[j].weight }) sorts by value/weight descending, which is correct. Others sort by weight or value incorrectly.Final Answer:
sort.Slice(items, func(i, j int) bool { return items[i].value/items[i].weight > items[j].value/items[j].weight }) -> Option CQuick Check:
Sort by value/weight descending = sort.Slice(items, func(i, j int) bool { return items[i].value/items[i].weight > items[j].value/items[j].weight }) [OK]
- Sorting by weight only
- Sorting by value only
- Using ascending order instead of descending
type Item struct {
value, weight float64
}
items := []Item{{60, 10}, {100, 20}, {120, 30}}
capacity := 50.0
// Sort by value/weight descending
sort.Slice(items, func(i, j int) bool {
return items[i].value/items[i].weight > items[j].value/items[j].weight
})
var totalValue float64
for _, item := range items {
if capacity == 0 {
break
}
if item.weight <= capacity {
capacity -= item.weight
totalValue += item.value
} else {
fraction := capacity / item.weight
totalValue += item.value * fraction
capacity = 0
}
}
fmt.Printf("%.2f", totalValue)Solution
Step 1: Sort items by value/weight ratio
Ratios: 60/10=6, 100/20=5, 120/30=4. Sorted order: {60,10}, {100,20}, {120,30}.Step 2: Pick items until capacity 50
Take full {60,10} (capacity=40, value=60), full {100,20} (capacity=20, value=160), then fraction of {120,30} with 20 weight (fraction=20/30=2/3), value added=120*(2/3)=80, total=240.Final Answer:
240.00 -> Option AQuick Check:
Total value = 60 + 100 + 80 = 240.00 [OK]
- Not sorting by value/weight ratio
- Taking items without checking capacity
- Incorrect fraction calculation
type Item struct {
value, weight float64
}
items := []Item{{60, 10}, {100, 20}, {120, 30}}
capacity := 50.0
sort.Slice(items, func(i, j int) bool {
return items[i].value > items[j].value
})
var totalValue float64
for _, item := range items {
if capacity == 0 {
break
}
if item.weight <= capacity {
capacity -= item.weight
totalValue += item.value
} else {
fraction := capacity / item.weight
totalValue += item.value * fraction
capacity = 0
}
}
fmt.Printf("%.2f", totalValue)Solution
Step 1: Analyze sorting criteria
The code sorts by value only, which is incorrect for fractional knapsack; it should sort by value/weight ratio.Step 2: Identify correct fix
Sorting by value/weight ratio descending ensures maximum value per weight is chosen first, fixing the bug.Final Answer:
Sort items by value/weight ratio descending instead of value only -> Option BQuick Check:
Sort by value/weight ratio fixes selection [OK]
- Sorting by value only
- Ignoring fraction calculation
- Changing variable types unnecessarily
Solution
Step 1: Calculate value/weight ratios and sort items
Ratios: 40/2=20, 100/20=5, 50/10=5. Sorted order: {40,2}, {100,20}, {50,10}.Step 2: Pick items until capacity 15
Take full {40,2} (capacity=13, value=40), then full {50,10} (capacity=3, value=90), then fraction of {100,20} with 3 weight (fraction=3/20=0.15), value added=100*0.15=15, total=40 + 50 + 15=105.Final Answer:
105.00 -> Option AQuick Check:
Total value = 40 + 50 + 15 = 105.00 [OK]
- Not sorting by value/weight ratio
- Taking heavier items first
- Incorrect fraction calculation
Ready to prove it?
Pass the test and this pattern moves unknown
