Solve the fractional knapsack problem using a greedy algorithm. Select items by their value-to-weight ratio to maximize total value within a weight capacity.
The fractional knapsack problem allows items to be divided into fractional parts. The greedy strategy sorts items by value-to-weight ratio in descending order, then fills the knapsack by selecting items with highest ratio first. This greedy choice always yields the optimal solution for this variant.
Given an array items where items[i] = [weighti, valuei], and an integer capacity representing maximum weight the knapsack can hold, return the maximum total value you can place in the knapsack.
You may take an item fully or take any fraction of it. The value gained from a fraction is proportional to the fraction taken.
Required Output: A floating-point number representing the maximum achievable value.
Example 1:
Input: items = [[10,60],[20,100],[30,120]], capacity = 50 Output: 240.00 Explanation: - Ratios: 6.0, 5.0, 4.0 - Take item [10,60] fully, item [20,100] fully - Remaining capacity = 20, take 20/30 of [30,120] = 80 - Total = 60 + 100 + 80 = 240
Example 2:
Input: items = [[5,30],[10,40],[20,100]], capacity = 15 Output: 80.00 Explanation: - Ratios: 6.0, 4.0, 5.0 -> sorted as [5,30], [20,100], [10,40] - Take [5,30] fully - Remaining capacity = 10, take 10/20 of [20,100] = 50 - Total = 30 + 50 = 80.00
Constraints:
Selection State
| Item | Weight | Value | Ratio | Status |
|---|
Total Value & Weight
Value: 0.0 | Weight: 0.0
Step Info
Waiting to solve...
Algorithm & Pseudocode
| Aspect | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(n) |
| Greedy Choice | Max Ratio |
Implementation
typedef struct: Defines Item structure holding weight and value as doubles for fractional calculations.
compare(): Comparator for qsort computes value/weight ratio on-the-fly for each item pair, returns 1 or -1 to sort descending by ratio. Essential for greedy selection.
qsort(): Standard library function performs sorting in O(n log n) time. Pass items array, count, size of each element, and comparator function pointer.
Main Loop: Iterates through sorted items in order of best ratio. If item fits fully, add entire value; else calculate fractional part and break (greedy fill).
Fractional Calculation: Line 19 computes (remaining_capacity / item_weight) * item_value—the maximum value achievable by partially taking an item.
Time Complexity: O(n log n) dominated by sorting; greedy iteration is O(n). Space O(n) for storing items.