📖 Scenario: You are helping a delivery company pack valuable items into a truck. Each item has a weight and a value. The truck can carry only a limited weight. To maximize profit, you can take whole items or fractions of items.
🎯 Goal: Build a program that calculates the maximum total value that fits into the truck using the fractional knapsack approach.
📋 What You'll Learn
Create a list of items with exact weights and values
Add a variable for the truck's maximum weight capacity
Implement the fractional knapsack logic to maximize value
Print the maximum total value with two decimal places
💡 Why This Matters
🌍 Real World
This problem models packing limited space with valuable goods, like loading trucks or cargo planes efficiently.
💼 Career
Understanding greedy algorithms like fractional knapsack is useful in logistics, resource allocation, and optimization roles.
Progress0 / 4 steps
1
Create the list of items
Create a list of tuples called items with these exact entries: (weight: 10, value: 60), (weight: 20, value: 100), (weight: 30, value: 120).
DSA C#
Hint
Use a List of tuples with weight and value fields.
2
Add the truck's weight capacity
Add an integer variable called capacity and set it to 50.
DSA C#
Hint
Use int capacity = 50; to set the truck's weight limit.
3
Implement the fractional knapsack logic
Sort the items list by value per weight in descending order. Then create a double variable totalValue set to 0. Use a foreach loop with variable item to iterate over items. Inside the loop, if capacity is zero, break the loop. Otherwise, take the minimum of capacity and item.weight as weightTaken. Add weightTaken * (item.value / (double)item.weight) to totalValue. Subtract weightTaken from capacity.
DSA C#
Hint
Sort by value/weight ratio, then pick items or fractions until capacity is full.
4
Print the maximum total value
Print the totalValue variable formatted to two decimal places using Console.WriteLine($"{totalValue:F2}").
DSA C#
Hint
Use Console.WriteLine($"{totalValue:F2}") to print the result with two decimals.
Practice
(1/5)
1. What is the main goal of the Fractional Knapsack Problem?
easy
A. Maximize number of items regardless of weight
B. Maximize total value by taking fractions of items within weight limit
C. Minimize total weight by selecting whole items only
D. Select items randomly without considering value or weight
Solution
Step 1: Understand the problem goal
The fractional knapsack problem allows taking parts of items to maximize total value within a weight limit.
Step 2: Compare options
Only Maximize total value by taking fractions of items within weight limit correctly states maximizing total value by taking fractions within weight limit.
Final Answer:
Maximize total value by taking fractions of items within weight limit -> Option B
Quick Check:
Goal = Maximize value with fractions [OK]
Hint: Remember: fractional means partial items allowed [OK]
Common Mistakes:
Thinking only whole items can be taken
Confusing with minimizing weight
Ignoring value-to-weight ratio
2. Which C# syntax correctly declares a class named Item with public fields weight and value?
easy
A. class Item { public int weight; public int value; }
B. class Item { int weight; int value; }
C. public Item { int weight; int value; }
D. class Item { public weight; public value; }
Solution
Step 1: Check class declaration syntax
In C#, class fields must have type and access modifier for public fields.
Step 2: Validate each option
class Item { public int weight; public int value; } correctly declares public int fields. class Item { int weight; int value; } lacks access modifier. public Item { int weight; int value; } misses class keyword. class Item { public weight; public value; } misses types.
Final Answer:
class Item { public int weight; public int value; } -> Option A
Quick Check:
Correct class syntax = class Item { public int weight; public int value; } [OK]
Hint: Public fields need type and access modifier [OK]
Common Mistakes:
Omitting access modifiers
Missing data types
Incorrect class keyword usage
3. What is the output of this C# code snippet for fractional knapsack?
var items = new[] {
new Item { weight = 10, value = 60 },
new Item { weight = 20, value = 100 },
new Item { weight = 30, value = 120 }
};
int capacity = 50;
double maxValue = 0;
Array.Sort(items, (a, b) => (b.value / (double)b.weight).CompareTo(a.value / (double)a.weight));
int remaining = capacity;
foreach (var item in items) {
if (item.weight <= remaining) {
maxValue += item.value;
remaining -= item.weight;
} else {
maxValue += item.value * (remaining / (double)item.weight);
break;
}
}
Console.WriteLine(Math.Round(maxValue, 2));
Take Item1 fully (weight 10, value 60), remaining=40. Take Item2 fully (weight 20, value 100), remaining=20. Take 20/30 fraction of Item3: value = 120 * (20/30) = 80.
Step 3: Calculate total value
Total = 60 + 100 + 80 = 240. Rounded to 240.00.
Final Answer:
240.00 -> Option D
Quick Check:
Sum values with fractions = 240.00 [OK]
Hint: Sort by value/weight, take full then fraction [OK]
Common Mistakes:
Not sorting by value/weight ratio
Taking items without fraction
Incorrect fraction calculation
4. Identify the bug in this fractional knapsack code snippet:
int capacity = 50;
var items = new List<Item> {
new Item { weight = 10, value = 60 },
new Item { weight = 20, value = 100 },
new Item { weight = 30, value = 120 }
};
items.Sort((a, b) => (a.value / a.weight).CompareTo(b.value / b.weight));
double maxValue = 0;
int remaining = capacity;
foreach (var item in items) {
if (item.weight <= remaining) {
maxValue += item.value;
remaining -= item.weight;
} else {
maxValue += item.value * (remaining / item.weight);
break;
}
}
Console.WriteLine(maxValue);
medium
A. Sorting order is ascending instead of descending
B. Missing check for zero weight items
C. Integer division causes incorrect ratio calculation
D. Using List instead of array causes error
Solution
Step 1: Analyze sorting comparator
The comparator uses integer division (a.value / a.weight) which truncates decimals, causing wrong ratios.
Step 2: Impact on sorting and calculation
Integer division leads to incorrect sorting order and wrong maxValue calculation.
Final Answer:
Integer division causes incorrect ratio calculation -> Option C
Quick Check:
Use double division for correct ratios [OK]
Hint: Use double division for ratios, not integer division [OK]
Common Mistakes:
Sorting ascending instead of descending
Ignoring integer division truncation
Assuming List causes error
5. Given items with weights and values: [(5, 30), (10, 40), (15, 45)], and knapsack capacity 20, what is the maximum value achievable using fractional knapsack?