Fractional knapsack and the limits of greedy
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fractional knapsack is solved optimally with greedy density sorting, while discrete knapsack requires dynamic programming.
Fractional knapsack and value density sorting
In the knapsack problem, a bag holds at most W total weight. Each item has a given weight and value. In fractional knapsack, items can be divided into arbitrary fractions.
Step by step
Step 1 of 4
- weight
- 10
- capacityLeft
- 40
- totalVal
- 60
Example 1 · Fractional Knapsack Solution
import java.util.Arrays;
public class FractionalKnapsackDemo { static class Item { double weight, value, density; Item(double w, double v) { this.weight = w; this.value = v; this.density = v / w; } }
public static double getMaxValue(double[] weights, double[] values, double capacity) { int n = weights.length; Item[] items = new Item[n]; for (int i = 0; i < n; i++) { items[i] = new Item(weights[i], values[i]); } Arrays.sort(items, (a, b) -> Double.compare(b.density, a.density));
double totalValue = 0.0; for (Item item : items) { if (capacity <= 0) break; if (item.weight <= capacity) { totalValue += item.value; capacity -= item.weight; } else { totalValue += item.density * capacity; capacity = 0; } } return totalValue; }
public static void main(String[] args) { double[] w = {10, 20, 30}; double[] v = {60, 100, 120}; double capacity = 50; System.out.printf("Max fractional value: %.1f\n", getMaxValue(w, v, capacity)); }}Max fractional value: 240.0
What this code does
- Takes item 1 completely (value 60, remaining capacity 40).
- Takes item 2 completely (value 100, remaining capacity 20).
- Takes 20/30 fraction of item 3 (value 80), reaching 240 total value.
Calculate the value density for each item by dividing value by weight. Sort items by value density in descending order. Greedily pack whole items as long as remaining capacity allows. When an item exceeds the remaining capacity, take a fraction of it. The fraction taken equals remaining capacity divided by item weight. This greedy strategy guarantees the maximum possible total value. Sorting dominates the runtime, taking log-linear time.
Order of execution
Fractional knapsack
Tap the steps of the greedy solution in order.
Why 0/1 knapsack breaks greedy and requires dynamic programming
In 0/1 knapsack, each item must be taken whole or left behind completely. Dividing items into fractions is strictly prohibited. Density-based greedy sorting fails here because indivisibility leaves wasted capacity.
Example 2 · Comparing Greedy and Dynamic Programming on 0/1 Knapsack
public class Knapsack01ComparisonDemo { public static int knapsackDP(int[] w, int[] v, int capacity) { int n = w.length; int[][] dp = new int[n + 1][capacity + 1]; for (int i = 1; i <= n; i++) { for (int cap = 0; cap <= capacity; cap++) { dp[i][cap] = dp[i - 1][cap]; if (cap >= w[i - 1]) { dp[i][cap] = Math.max(dp[i][cap], dp[i - 1][cap - w[i - 1]] + v[i - 1]); } } } return dp[n][capacity]; }
public static void main(String[] args) { int[] w = {10, 20, 30}; int[] v = {60, 100, 120}; int capacity = 50; // Greedy picks item 1 (10, 60) + item 2 (20, 100) = 160 int dpVal = knapsackDP(w, v, capacity); System.out.println("Greedy 0/1 value: 160"); System.out.println("Optimal DP value: " + dpVal); }}Greedy 0/1 value: 160 Optimal DP value: 220
What this code does
- Greedy selects item 1 and 2, wasting 20 units of capacity with value 160.
- Dynamic programming selects item 2 (weight 20) and item 3 (weight 30), yielding 220.
- Shows why indivisibility requires dynamic programming instead of greedy.
Consider capacity 50 with three items. Item 1 has weight 10 and value 60 with density 6. Item 2 has weight 20 and value 100 with density 5. Item 3 has weight 30 and value 120 with density 4. Greedy selects item 1 and item 2, giving value 160 and weight 30. The remaining 20 capacity cannot fit item 3 of weight 30. However, selecting items 2 and 3 gives total weight 50 and value 220. Greedy missed 60 value because it could not fill the leftover space.
Canonical currency systems and greedy boundaries
A similar breakdown occurs in coin change problems. In standard currency systems, greedy selection always yields the minimal coin count. Each larger denomination is a multiple or structured combination of smaller coins.
Example 3 · Coin Change Greedy Versus DP Breakdown
import java.util.Arrays;
public class CoinChangeGreedyVsDpDemo { public static int greedyCoins(int[] coins, int amount) { int count = 0; for (int i = coins.length - 1; i >= 0; i--) { while (amount >= coins[i]) { amount -= coins[i]; count++; } } return amount == 0 ? count : -1; }
public static int dpCoins(int[] coins, int amount) { int[] dp = new int[amount + 1]; Arrays.fill(dp, amount + 1); dp[0] = 0; for (int a = 1; a <= amount; a++) { for (int c : coins) { if (a >= c) { dp[a] = Math.min(dp[a], dp[a - c] + 1); } } } return dp[amount] > amount ? -1 : dp[amount]; }
public static void main(String[] args) { int[] customCoins = {1, 3, 4}; int amount = 6; System.out.println("Greedy coins: " + greedyCoins(customCoins, amount)); System.out.println("DP optimal coins: " + dpCoins(customCoins, amount)); }}Greedy coins: 3 DP optimal coins: 2
What this code does
- Greedy selects coin 4, then coin 1, then coin 1, using 3 coins.
- Dynamic programming finds the optimal combination of two coins: 3 + 3 = 6.
- Illustrates the boundary where greedy fails due to discrete combinations.
However, arbitrary coin systems break the greedy choice property. For coins 1, 3, and 4, target 6 produces three coins with greedy: 4, 1, 1. The true optimum uses two coins: 3 and 3. Whenever decisions are discrete and leave irreversible gaps, greedy fails. Dynamic programming solves these problems by evaluating all valid combinations. Always verify whether discrete boundaries allow greedy exchange arguments to hold.
Next step
Check your understanding
10 quick questions