📖 Scenario: You are helping a delivery company pack valuable items into a knapsack. Each item has a weight and a value. The knapsack can carry a limited weight. To maximize profit, you can take fractions of items.
🎯 Goal: Build a program that calculates the maximum total value that fits into the knapsack by taking whole or fractional parts of items.
📋 What You'll Learn
Create an array of items with exact weights and values
Add a variable for the knapsack's maximum weight capacity
Implement the fractional knapsack logic to maximize total value
Print the maximum total value with two decimal places
💡 Why This Matters
🌍 Real World
This problem models packing cargo, loading trucks, or resource allocation where partial quantities can be chosen.
💼 Career
Understanding greedy algorithms like fractional knapsack is important for optimization tasks in software engineering and data science.
Progress0 / 4 steps
1
Create the items array
Create an array called items with these exact objects: { weight: 10, value: 60 }, { weight: 20, value: 100 }, { weight: 30, value: 120 }
DSA Typescript
Hint
Use an array of objects with weight and value properties.
2
Set the knapsack capacity
Create a variable called capacity and set it to 50
DSA Typescript
Hint
Use a simple number variable for the knapsack's weight limit.
3
Implement fractional knapsack logic
Write code to calculate the maximum total value by sorting items by value per weight, then taking whole or fractional parts until capacity is full. Store the result in a variable called maxValue
DSA Typescript
Hint
Sort items by value/weight ratio descending. Use a loop to add full or fractional items until capacity is used.
4
Print the maximum total value
Print the variable maxValue rounded to two decimal places using console.log(maxValue.toFixed(2))
DSA Typescript
Hint
Use console.log(maxValue.toFixed(2)) to print the result with two decimals.
Practice
(1/5)
1. What is the main goal of the Fractional Knapsack Problem?
easy
A. Maximize total value by taking fractions of items within weight limit
B. Minimize total weight of items selected
C. Select only whole items to maximize value
D. Sort items by weight only
Solution
Step 1: Understand problem goal
The fractional knapsack problem allows taking parts of items to maximize value within a weight limit.
Step 2: Compare options
Maximize total value by taking fractions of items within weight limit correctly states maximizing total value by taking fractions. Others focus on minimizing weight or whole items only, which is incorrect.
Final Answer:
Maximize total value by taking fractions of items within weight limit -> Option A
Quick Check:
Fractional knapsack = maximize value with fractions [OK]
Hint: Remember: fractional means partial items allowed [OK]
Common Mistakes:
Thinking only whole items can be taken
Confusing minimization with maximization
Ignoring fractional parts of items
2. Which TypeScript syntax correctly declares an array of objects representing items with weight and value for the fractional knapsack?
easy
A. var items = weight: 10, value: 60; weight: 20, value: 100;
B. let items = (weight: 10, value: 60), (weight: 20, value: 100);
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. Total value = 60 + 100 + 80 = 240.
Step 3: Check options
Matches 240.
Final Answer:
240 -> Option C
Quick Check:
Sum values with fractions = 240 [OK]
Hint: Sort by value/weight ratio, take full items first [OK]
Common Mistakes:
Not sorting items by value/weight ratio
Taking items without fractions
Incorrect fraction calculation
4. Identify the bug in this TypeScript function for fractional knapsack:
function fractionalKnapsack(items, capacity) {
items.sort((a, b) => (a.value / a.weight) - (b.value / b.weight));
let totalValue = 0;
let remaining = capacity;
for (const item of items) {
if (item.weight <= remaining) {
totalValue += item.value;
remaining -= item.weight;
} else {
totalValue += item.value * (remaining / item.weight);
break;
}
}
return totalValue;
}
medium
A. Using 'let' instead of 'const' for totalValue
B. Sorting order is ascending instead of descending by value/weight
C. Missing return statement
D. Incorrect fraction calculation in else block
Solution
Step 1: Analyze sorting function
The sort compares (a.value/a.weight) - (b.value/b.weight), which sorts ascending by ratio.
Step 2: Understand impact on knapsack
Fractional knapsack requires descending order to pick highest value/weight first. Ascending order causes wrong selection.
Final Answer:
Sorting order is ascending instead of descending by value/weight -> Option B
Quick Check:
Sort descending by ratio [OK]
Hint: Sort descending by value/weight ratio, not ascending [OK]
Common Mistakes:
Sorting ascending instead of descending
Ignoring sorting impact on result
Confusing variable declarations
5. Given items with weights and values: [{weight: 5, value: 30}, {weight: 10, value: 40}, {weight: 20, value: 140}], and a knapsack capacity of 15, what is the maximum value achievable using the fractional knapsack approach?
hard
A. 105
B. 90
C. 120
D. 100
Solution
Step 1: Calculate value/weight ratios and sort descending