Cracking the Code: Your First Dive into the Fractional Knapsack Problem
Jun 07, 2026 7 Min Read 44 Views
(Last Updated)
Picture this: you’re packing for a hike with a 10 kg capacity backpack and a pile of supplies food, medicine, tools each with different weight and value. You want the maximum total value but can’t carry everything, so you pick items offering the highest value per kilogram and, if necessary, take a fraction of an item (split a food packet) to fill the pack. That simple “take the best value-per-weight first” rule is the heart of the fractional knapsack problem.
This problem is a classic example of greedy algorithms, where you make the locally optimal choice at every step hoping to reach the global optimum. Unlike many greedy problems, the fractional knapsack’s greedy strategy is provably optimal: sorting items by value-to-weight ratio and taking them in that order (fractionally when needed) yields the maximum possible value for the given capacity.
In this article, we will break down the fractional knapsack problem from the ground up, walk through how the algorithm works, look at a step-by-step numerical example, see Python and C code implementations, understand why greedy works here but not everywhere, and explore where this concept shows up in the real world.
Table of contents
- TL;DR
- Understanding the Problem Statement
- The Core Idea: Value-to-Weight Ratio of Fractional Knapsack
- The Greedy Algorithm: Step by Step for Fractional Knapsack
- Step one:
- Step two :
- Step three :
- A Worked Example with Numbers of Fractional Knapsack
- Python Code Implementation of Fractional Knapsack
- C Code Implementation of Fractional Knapsack
- Why Does Greedy Work Here but Not in 0/1 Knapsack?
- Fractional vs. 0/1 Knapsack: Key Differences
- Real-World Applications
- Common Mistakes to Avoid
- FAQ
- Why sort by value-to-weight ratio rather than value or weight alone?
- What is the algorithm’s time and space complexity?
- How many items might be partially taken?
- Can I use the greedy method for 0/1 knapsack?
- How should I handle items with zero weight or zero value?
TL;DR
- Fractional Knapsack lets you take fractions of items to maximize total value under a weight capacity; the optimal strategy is greedy.
- Compute each item’s value-to-weight ratio, sort items by descending ratio, then take items fully until the remaining capacity forces a fractional take.
- Time complexity is O(n log n) (sorting); you only ever split at most one item.
- Greedy works here because divisibility removes packing constraints that break greedy in the 0/1 knapsack (which needs dynamic programming).
- Real applications include resource allocation for divisible goods (fuel, bulk materials), portfolio allocation, and logistical loading problems.
What Is the Fractional Knapsack Problem?
The fractional knapsack problem is an optimization problem in which a bag with limited carrying capacity must be filled with items that have different weights and values in order to maximize the total value carried. Unlike the 0/1 knapsack problem, items can be divided, allowing fractions of an item to be taken instead of requiring a full item selection. The optimal solution uses a greedy strategy by selecting items in decreasing order of their value-to-weight ratio until the knapsack is full.
Understanding the Problem Statement
- Problem setup
You have n items; each item has a value and a weight. You also have a knapsack with a fixed maximum weight capacity. Choose items (or parts of items) so that the total weight ≤ capacity and the total value is maximised. - Fractional items allowed
In the fractional knapsack variant, you may take fractions of items. If only part of an item fits, you can include that fraction and receive the proportional value. This ability to split items is the defining difference from the 0/1 knapsack. - Impact on solution approach
Allowing fractions makes the problem solvable optimally with a greedy strategy: sort items by value-per-weight (density) and take the highest-density items first, using partial items as needed to fill remaining capacity.
The Core Idea: Value-to-Weight Ratio of Fractional Knapsack
Before we get into the algorithm, there is one concept you need to lock down: the value-to-weight ratio. This is simply the value of an item divided by its weight, and it tells you how much value you get for every single unit of weight you spend carrying that item.
Think about it this way. Suppose you have two items:
- Item A has a value of 100 and weighs 50 kg. That gives a ratio of 2. Item B has a value of 60 and weighs 10 kg. That gives a ratio of 6.
- Even though Item A has a higher total value, Item B gives you more value per kg. If you are working with a limited weight budget, Item B is the smarter pick.
- The fractional knapsack algorithm is built entirely on this observation.
- To maximise value, we should always prefer items with the highest value-to-weight ratio first.
- If we are allowed to take fractions of an item, then we can always pick as much as possible from the item that gives the best value per unit weight.
The Greedy Algorithm: Step by Step for Fractional Knapsack
The greedy algorithm for solving the Fractional Knapsack Problem is built around three simple steps, and it is very approachable once you understand what each step is doing.
Step one:
It is to calculate the value-to-weight ratio for every item. This is just a division operation value divided by weight, and you do it for each item in your list.
Step two :
It is to sort all the items in descending order based on their ratio. The item with the highest ratio comes first, the next highest comes second, and so on. This sorting step is what ensures you always consider the most profitable item at each point.
Step three :
This is to traverse the sorted list. Add the whole item if it fits within the remaining capacity. If an item does not fully fit, add the fractional part of the item that fills the remaining capacity and stop the process. This algorithm guarantees the maximum possible value for the given knapsack capacity.
The reason you stop after taking a fraction is that once you have used up the last bit of capacity, the knapsack is full and there is nothing more to add. You will only ever need to break one item into a fraction; all items before it are taken completely, and all items after it are left behind.
A Worked Example with Numbers of Fractional Knapsack
Let us walk through a concrete example so everything clicks.
Suppose you have three items and a knapsack with a capacity of 50 kg.
| Item | Weight | Value |
| 1 | 10 | 60 |
| 2 | 20 | 100 |
| 3 | 30 | 120 |
- First, calculate the value-to-weight ratios: Item 1: 60 ÷ 10 = 6.0 Item 2: 100 ÷ 20 = 5.0 Item 3: 120 ÷ 30 = 4.0
- Sorted in descending order, the sequence is: Item 1, Item 2, Item 3.
- Now fill the knapsack:
- Take all of Item 1 weight 10, value 60. Remaining capacity: 40. Take all of Item 2 weight 20, value 100. Remaining capacity: 20. Item 3 weighs 30 but only 20 kg of space is left. Take 20/30 = two-thirds of Item 3. Fractional value = 120 × (20/30) = 80.
- Total value = 60 + 100 + 80 = 240. This shows why the greedy approach is important here a naive choice might only yield 220 by picking items 2 and 3 fully, missing the better combination entirely.
- The greedy approach found the maximum possible value of 240 by always prioritizing the item with the best return per unit of weight.
Although often taught as a simple algorithmic problem, the fractional knapsack problem models many real-world resource allocation scenarios where resources can be divided continuously. Examples include investment portfolio allocation, bulk cargo loading, bandwidth distribution, and prioritizing supplies during disaster relief operations. One reason the problem is so important in computer science is that its greedy strategy—choosing items by the highest value-to-weight ratio first—is mathematically proven to produce a globally optimal solution. This makes it a classic example where making the locally best choice at every step guarantees the best overall outcome.
Python Code Implementation of Fractional Knapsack
Here is how you would implement this algorithm in Python:
class Solution:
def fractionalKnapsack(self, val, wt, capacity):
# Build list of (ratio, value, weight) for each item
items = [(v / w, v, w) for v, w in zip(val, wt) if w > 0]
# Sort by ratio in descending order
items.sort(key=lambda x: x[0], reverse=True)
total_value = 0.0
cur_weight = 0
for ratio, v, w in items:
if cur_weight + w <= capacity:
cur_weight += w
total_value += v
else:
remain = capacity – cur_weight
if remain <= 0:
break
total_value += ratio * remain
break # knapsack is full
return total_value
The logic is straightforward. You first build a list that pairs each item with its ratio. After sorting, you loop through and either take the full item or just the fractional portion needed to fill the remaining space.
The process stops as soon as the knapsack reaches full capacity. This approach ensures that we are always choosing the most profitable option at every step, which is why greedy works here.
C Code Implementation of Fractional Knapsack
For those working in C, here is the equivalent implementation:
#include <stdio.h>
struct Item {
int weight;
int value;
};
void sortItems(struct Item arr[], int n) {
for (int i = 0; i < n – 1; i++) {
for (int j = 0; j < n – i – 1; j++) {
double r1 = (double)arr[j].value / arr[j].weight;
double r2 = (double)arr[j + 1].value / arr[j + 1].weight;
if (r1 < r2) {
struct Item temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
double fractionalKnapsack(struct Item items[], int n, int capacity) {
sortItems(items, n);
double totalValue = 0.0;
for (int i = 0; i < n; i++) {
if (capacity >= items[i].weight) {
capacity -= items[i].weight;
totalValue += items[i].value;
} else {
totalValue += items[i].value * ((double)capacity / items[i].weight);
break;
}
}
return totalValue;
}
int main() {
struct Item items[] = {{10, 60}, {20, 100}, {30, 120}};
int n = 3;
int capacity = 50;
printf(“Maximum value = %.2f\n”, fractionalKnapsack(items, n, capacity));
return 0;
}
Output: Maximum value = 240.00
The C program defines a structure to store the weight and value of each item, sorts them using bubble sort based on the value-to-weight ratio, and then fills the knapsack taking full items when they fit and fractional portions when they do not.
Why Does Greedy Work Here but Not in 0/1 Knapsack?
This is one of the most important conceptual questions to understand, and it is something that often comes up in interviews.knapsack, taking
- In the Fractional Knapsack Problem, you can always make use of every bit of remaining capacity. If the next best item does not fully fit, you take a fraction of it.
- This means you never waste any space. The greedy choice always take the highest-ratio item is always the right one because you can precisely fill the knapsack to its edge using fractions.
- In the 0/1 Knapsack Problem, items cannot be broken. You either take an item whole or leave it.
- This means the greedy approach can fail badly because taking a high-ratio item might leave an awkward gap in the bag that no remaining item can fill exactly, while a different combination of lower-ratio items might pack together perfectly and yield a higher total value.
- The greedy approach works in the fractional knapsack problem because we are allowed to take fractions of items.
- This means we can always pick the item with the highest value-to-weight ratio first and maximize profit at every step.
- In the 0/1 Knapsack problem, items must be either fully taken or completely left. Greedy works for Fractional Knapsack but not for 0/1 Knapsack.
- The 0/1 version requires dynamic programming a technique where you build a table of solutions to smaller sub-problems to find the best combination. Its time complexity is O(n × W) where W is the knapsack capacity, which is significantly more expensive than the O(n log n) greedy solution used here.
Fractional vs. 0/1 Knapsack: Key Differences
| Aspect | Fractional Knapsack | 0/1 Knapsack |
| Item division | Items can be split | Items are indivisible |
| Algorithm | Greedy | Dynamic Programming |
| Time complexity | O(n log n) | O(n × W) |
| Greedy optimal? | Yes, always | No |
| Memory needed | Minimal | Requires a DP table |
| Real-world fit | Liquids, sand, money | Electronics, products |
Real-World Applications
The fractional knapsack problem is not just an academic exercise. Its logic appears across a surprising range of real fields.
- In financial portfolio management, investors allocate a budget across different assets. Since money is divisible, you can invest any fraction of your capital in a given stock or bond. The goal is the same as the problem: to maximize return (value) for a given risk tolerance (weight capacity).
- In logistics and freight, shipping companies deal with weight limits on trucks or cargo planes. When items are divisible like bulk goods, liquids, or raw materials, they apply exactly this kind of ratio-based prioritization to decide how much of each shipment to load.
- In cloud computing and IT resource management, businesses must efficiently distribute scarce resources such as CPU time or storage within financial constraints. The fractional knapsack model optimizes these allocations for maximum utility.
- Disaster relief operations also follow this logic. When aid organizations have limited transport capacity and need to distribute food, water, and medicine to affected areas, they prioritize supplies by their value-to-weight efficiency exactly mirroring the algorithm.
Common Mistakes to Avoid
- One common error beginners make is sorting items by value instead of by value-to-weight ratio. Sorting by total value alone will not give you the optimal solution because a very valuable but very heavy item may crowd out multiple lighter, high-ratio items that together would yield more total value.
- Another mistake is forgetting to handle the fractional case. Some implementations stop as soon as an item does not fit, without taking the partial portion. This leaves space wasted in the knapsack and produces a suboptimal result.
- Also, watch out for items with zero weight in your input data. Dividing by zero when calculating the ratio will crash your program. A simple check to skip such items handles this edge case cleanly, as shown in the Python implementation above.
Loved diving into the fractional knapsack problem? Turn that understanding into real coding skills and master greedy algorithms, dynamic programming, and more in HCL GUVI’s Programming Course.
Summary
The Fractional Knapsack Problem teaches you one of the most powerful ideas in algorithm design that making the locally optimal choice at every step can sometimes lead to the globally optimal outcome. The value-to-weight ratio is the key insight that drives the entire solution. Sort by it, pick greedily, and take fractions when needed. Three steps, one pass, and you have the best possible answer every time.
It is elegant, efficient at O(n log n), and directly applicable to real-world optimization scenarios in finance, logistics, and resource management. If you are preparing for coding interviews or building your foundation in algorithms, the Fractional Knapsack Problem is one of those topics that genuinely earns its place on your must-know list.
FAQ
1. Why sort by value-to-weight ratio rather than value or weight alone?
The ratio captures how much value each unit of weight yields. Sorting by total value can pick heavy items that block better combinations; sorting by ratio ensures each unit of capacity gives maximal value.
2. What is the algorithm’s time and space complexity?
Time: O(n log n) dominated by sorting. Space: O(n) for storing items and their ratios (or O(1) extra if sorting in place).
3. How many items might be partially taken?
At most one item is taken fractionally the first item that doesn’t fit entirely into the remaining capacity.
4. Can I use the greedy method for 0/1 knapsack?
No. Greedy can fail for 0/1 knapsack because items are indivisible and packing interactions matter. 0/1 knapsack requires dynamic programming (O(n × W)) for optimality.
5. How should I handle items with zero weight or zero value?
Skip items with zero weight (avoid division by zero) and treat zero-value items as useless. If an input may include zero-weight items, validate or filter them before computing ratios.



Did you enjoy this article?