Back to Practice Dashboard
Competitive ProgrammingEasy
Fractional Knapsack
Learn how to solve the 'Fractional Knapsack' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Easy
Write a function fractional_knapsack(W, items) that takes the knapsack capacity W and a list of tuples items where each tuple is (value, weight). Find the maximum total value obtainable in the knapsack, allowing items to be broken/fractioned. Round the output to 2 decimal places.
Constraints
- •1 <= len(items) <= 1000
- •1 <= W <= 10^5
- •1 <= value, weight <= 10^4
Examples
Example 1
Input
fractional_knapsack(50, [(60, 10), (100, 20), (120, 30)])
Output
240.0
Explanation
Take the first and second item fully, and 2/3 of the third item. Total value: 60 + 100 + 120 * (20/30) = 240.0.
Example 2
Input
fractional_knapsack(15, [(24, 10), (18, 10), (15, 10)])
Output
33.0
Explanation
Take the first item fully, and 1/2 of the second item. Total value: 24 + 18 * 0.5 = 33.0.
Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.