import java.util.*; class Item { int value, weight; Item(int v, int w) { value = v; weight = w; } } public class FractionalKnapsack { public static double getMaxValue(int W, Item[] items) { Arrays.sort(items, (a, b) -> Double.compare((double)b.value / b.weight, (double)a.value / a.weight)); double totalValue = 0.0; int capacity = W; for (Item item : items) { if (capacity == 0) break; if (item.weight <= capacity) { capacity -= item.weight; totalValue += item.value; } else { totalValue += item.value * ((double)capacity / item.weight); capacity = 0; } } return totalValue; } public static void main(String[] args) { Item[] items = {new Item(60, 10), new Item(100, 20), new Item(120, 30)}; int W = 50; System.out.printf("%.2f", getMaxValue(W, items)); } }
The items sorted by value/weight ratio are: (60/10=6), (100/20=5), (120/30=4). The knapsack capacity is 50.
Take all of item 1 (weight 10, value 60), capacity left 40.
Take all of item 2 (weight 20, value 100), capacity left 20.
Take 20/30 fraction of item 3: value = 120 * (20/30) = 80.
Total value = 60 + 100 + 80 = 240.
The fractional knapsack problem allows taking fractions of items, which enables a greedy strategy by selecting items with the highest value-to-weight ratio first.
import java.util.*; class Item { int value, weight; Item(int v, int w) { value = v; weight = w; } } public class FractionalKnapsack { public static double getMaxValue(int W, Item[] items) { Arrays.sort(items, (a, b) -> (b.value / b.weight) - (a.value / a.weight)); double totalValue = 0.0; int capacity = W; for (Item item : items) { if (capacity == 0) break; if (item.weight <= capacity) { capacity -= item.weight; totalValue += item.value; } else { totalValue += item.value * ((double)capacity / item.weight); capacity = 0; } } return totalValue; } }
The comparator uses integer division (b.value / b.weight) which truncates decimals, causing incorrect sorting order. This leads to wrong greedy selection and incorrect final value.
Value/weight ratios: 40/2=20, 100/20=5, 50/10=5.
Take all of item 1 (weight 2, value 40), capacity left 28.
Next items have same ratio 5, take all of item 3 (weight 10, value 50), capacity left 18.
Take 18/20 fraction of item 2: value = 100 * (18/20) = 90.
Total value = 40 + 50 + 90 = 180.
Fractional knapsack allows taking fractions of items, making it a continuous optimization problem solvable optimally by a greedy approach. Dynamic programming is used for discrete problems like 0/1 knapsack where items cannot be split.
