Competitive ProgrammingEasy

Fractional Knapsack

Detailed guide and Python implementation for the 'Fractional Knapsack' problem.

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?
Consider using Greedy-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.