Algorithm Fractional Knapsack Problem Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Algorithm Fractional Knapsack Problem

Key Concepts:

  1. Items and Characteristics:

    • Each item has a weight W[i] and a value V[i].
    • You aim to maximize total value while keeping the total weight ≤ capacity C.
  2. Fractional vs. Integer Knapsack:

    • Unlike the integer knapsack problem where you must either take or leave an item whole, in the fractional problem, you can take any fraction of an item.
  3. Greedy Algorithm:

    • The most effective approach to solve this problem is using a greedy algorithm.
    • The key idea is to pick the item with the highest value-to-weight ratio.
  4. Value-to-Weight Ratio Calculation:

    • For each item, calculate V[i]/W[i], which indicates how much value per unit weight you can get from the item.
  5. Sorting Items:

    • Sort all items based on their value-to-weight ratio in descending order.
  6. Selection Process:

    • Start adding items to the knapsack from this sorted list.
    • If the entire item can fit within the remaining capacity C, take it whole.
    • If not, take as much of the item as possible (i.e., only the fraction required to fill up the knapsack).
  7. Example:

    • Consider items with weights: [10, 20, 30], values: [60, 100, 120]. Knapsack capacity = 50.
    • Calculate ratios: [6, 5, 4], sort by ratio: [(10, 60), (20, 100), (30, 120)].
    • Select all 10-unit item; select all 20-unit item; then select 10/30 * 120 = 40 units of the 30-unit item.
    • Total value: 60 + 100 + 40 = 200.

Pseudocode:

function fractionalKnapsack(C, W, V):
    # Create a list of items as (value, weight) tuples
    items = [(V[i], W[i]) for i in range(len(W))]
    
    # Sort items by value-to-weight ratio (descending)
    items.sort(key=lambda x: x[0]/x[1], reverse=True)
    
    total_value = 0
    for value, weight in items:
        if C == 0: 
            break
        
        # Take as much as possible
        amount = min(weight, C)
        total_value += amount * (value / weight)
        C -= amount
    
    return total_value

Important Information:

  • Time Complexity: O(n log n) due to the sorting step, where n is the number of items.
  • Space Complexity: O(n) for storing the list of items.
  • Applicability: Problems where partial quantities of items can be chosen.
  • Limitations: Greedy algorithms do not guarantee optimal solutions for the integer version but work perfectly here.

Practical Uses:

  • Resource Allocation: Deciding how to allocate limited resources like time, money, or capacity efficiently.
  • Investment Decision-Making: Investing partially in different stocks to maximize returns.
  • Supply Chain Optimization: Managing inventory to maximize profit or minimize cost.

Real-world Scenario:

Imagine you're packing your backpack for a long trip and you have a limited capacity. You can carry a camera worth $200 weighing 10 kg, an MP3 player worth $180 weighing 20 kg, a laptop worth $1200 weighing 30 kg, etc. Since you can't break these items, you have to decide the best subset to carry. However, suppose you could take a fraction of each item. This would allow taking only parts of the laptop, for example, reducing the weight while maintaining a high value.

Step-by-Step Solution:

  1. Calculate Ratios: Compute value-to-weight ratios for each item.
  2. Sort Items: Arrange items in descending order based on these ratios.
  3. Iterate and Select: Go through the sorted list and add as much of each item as possible until the knapsack reaches full capacity.
  4. Compute Total Value: Accumulate the values from the selected portions.

Conclusion:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Algorithm Fractional Knapsack Problem

Let's walk through the problem with a complete example, step by step.

Example Problem Statement

Suppose you have the following items:

| Item | Weight (w) | Value (v) | |------|------------|-----------| | 1 | 10 | 60 | | 2 | 20 | 100 | | 3 | 30 | 120 |

You have a knapsack with a maximum weight capacity of 50 units.

Objective

Maximize the total value that can be carried in the knapsack without exceeding the weight limit of 50 units.

Step-by-Step Solution

Step 1: Calculate Value-to-Weight Ratio

To make a decision about which items to include, we first calculate the value-to-weight ratio for each item. This ratio helps us determine which item provides the most value per unit of weight.

| Item | Weight (w) | Value (v) | Value-to-Weight Ratio (v/w) | |------|------------|-----------|-----------------------------| | 1 | 10 | 60 | 60/10 = 6.00 | | 2 | 20 | 100 | 100/20 = 5.00 | | 3 | 30 | 120 | 120/30 = 4.00 |

Step 2: Sort Items by Value-to-Weight Ratio (Descending)

We sort the items based on their value-to-weight ratio in descending order. This sorting will help us prioritize items that offer the most value per unit of weight.

| Item | Weight (w) | Value (v) | Value-to-Weight Ratio (v/w) | |------|------------|-----------|-----------------------------| | 1 | 10 | 60 | 6.00 | | 2 | 20 | 100 | 5.00 | | 3 | 30 | 120 | 4.00 |

Step 3: Initialize Variables

Set the initial total weight and total value to zero.

  • Total Weight (Wcurrent) = 0
  • Total Value (Vcurrent) = 0

Step 4: Select Items Greedily

We iterate through the sorted list of items and add as much as possible of each item to the knapsack until the knapsack is full or we have considered all items.

  1. Consider Item 1:

    • Weight = 10
    • Value = 60
    • Wcurrent + 10 ≤ 50 (True), so add the entire item.
    • Wcurrent = Wcurrent + 10 = 0 + 10 = 10
    • Vcurrent = Vcurrent + 60 = 0 + 60 = 60
  2. Consider Item 2:

    • Weight = 20
    • Value = 100
    • Wcurrent + 20 ≤ 50 (True), so add the entire item.
    • Wcurrent = Wcurrent + 20 = 10 + 20 = 30
    • Vcurrent = Vcurrent + 100 = 60 + 100 = 160
  3. Consider Item 3:

    • Weight = 30
    • Value = 120
    • Wcurrent + 30 ≤ 50 (False), so we cannot add the entire item.
    • Available weight left in knapsack = 50 - Wcurrent = 50 - 30 = 20
    • Fraction of Item 3 to take = 20 / 30 = 2/3
    • Weight of fraction taken = (2/3) * 30 = 20
    • Value of fraction taken = (2/3) * 120 = 80
    • Wcurrent = Wcurrent + 20 = 30 + 20 = 50
    • Vcurrent = Vcurrent + 80 = 160 + 80 = 240

Step 5: Final Solution

After considering all items, the knapsack is full with the following details:

  • Total Weight in Knapsack (Wcurrent) = 50
  • Total Value in Knapsack (Vcurrent) = 240

Summary of Fractional Knapsack Solution

| Item | Fraction Taken | Weight Added | Value Added | |------|----------------|--------------|-------------| | 1 | 1 (whole) | 10 | 60 | | 2 | 1 (whole) | 20 | 100 | | 3 | 2/3 | 20 | 80 | | Total: | | 50 | 240 |

Conclusion

The Fractional Knapsack Problem can be efficiently solved using a greedy algorithm by sorting items based on their value-to-weight ratio and then adding them to the knapsack in descending order of the ratio, taking as much of each item as possible without exceeding the weight capacity.

This approach ensures that we maximize the total value in the knapsack. The time complexity of this algorithm is ( O(n \log n) ) due to the sorting step, where ( n ) is the number of items.

Additional Notes

  • Greedy Feasibility: The Fractional Knapsack Problem is a greedy problem because a locally optimal choice (choosing the item with the highest value-to-weight ratio first) leads to a globally optimal solution.
  • Fractional Items: Unlike the 0/1 Knapsack Problem, in the Fractional Knapsack Problem, we can take fractions of an item, which makes it easier to solve optimally using a greedy approach.

You May Like This Related .NET Topic

Login to post a comment.