Fractional Knapsack Problem
Pattern: Fractional knapsack
Items can be split, so fill the bag with the most valuable material per kilogram first. Sort by value / weight, take whole items while they fit, and take the right fraction of the first one that does not.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Each item has a value and a weight, and you may take any fraction of an item. Return the largest total value that
fits in a bag of the given capacity. The tests print it with four decimal places. Values [60, 100, 120], weights
[10, 20, 30], capacity 50 gives 240.0000.
The catalogue has no practice link for this one.
Think first
- Which kilogram of material is worth the most?
- Can taking part of an item ever hurt?
- When do you stop?
Hints
Brute force, and why it fails
Try every order of items, filling greedily: O(n! × n).
The key insight
Every kilogram is interchangeable, so each one should come from the best ratio still available.
Dry run
| order | 6 5 4 |
|---|
Values [60, 100, 120], weights [10, 20, 30], capacity 50. Ratios 6, 5, 4.
The plan
sort items by value / weight, highest first
for (v, w): take = min(w, left); total += v * take / w; left -= take
Complexity
- Time
O(n log n)- Space
O(n)
Sorting dominates.
Edge cases
- Capacity 0: 0.
- Everything fits: the sum of values.
- One item larger than the bag.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public double fractionalKnapsack(int[] val, int[] wt, int capacity) {
int n = val.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> Double.compare((double) val[b] / wt[b], (double) val[a] / wt[a])); // best value per kg first
double total = 0;
int left = capacity;
for (int i : order) {
if (left == 0) break;
int take = Math.min(wt[i], left); // all of it, or the part that still fits
total += (double) val[i] * take / wt[i];
left -= take;
}
return total;
}
}C++
class Solution {
public:
double fractionalKnapsack(vector<int>& val, vector<int>& wt, int capacity) {
int n = static_cast<int>(val.size());
vector<int> order(n);
for (int i = 0; i < n; i++) order[i] = i;
sort(order.begin(), order.end(), [&](int a, int b) {
return static_cast<double>(val[a]) / wt[a] > static_cast<double>(val[b]) / wt[b]; // best value per kg first
});
double total = 0;
int left = capacity;
for (int i : order) {
if (left == 0) break;
int take = min(wt[i], left); // all of it, or the part that still fits
total += static_cast<double>(val[i]) * take / wt[i];
left -= take;
}
return total;
}
};Python
class Solution:
def fractionalKnapsack(self, val: list[int], wt: list[int], capacity: int) -> float:
total, left = 0.0, capacity
for v, w in sorted(zip(val, wt), key=lambda p: -p[0] / p[1]): # best value per kg first
if left == 0:
break
take = min(w, left) # all of it, or the part that still fits
total += v * take / w
left -= take
return totalCommon mistakes
- Comparing ratios with integer division.
- Using this method for the 0/1 knapsack.