ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Design and Analysis of Algorithms
    COMP3138
    Progress0 / 53 topics
    Topics
    1. Introduction to Algorithm Design2. Data Structures3. Efficiency in Algorithms4. Analysis of Algorithms5. Mathematical Review6. Mathematical Analysis of Algorithms7. Types of Functions8. Order of Growth9. Asymptotic Notations10. Sorting Algorithms11. Selection Sort Algorithm12. Example and Analysis of Selection Sort13. Insertion Sort Algorithm14. Divide and Conquer Algorithms15. Merge Sort Algorithm16. Quick Sort Algorithm17. Bucket Sort Algorithm18. Radix Sort Algorithm19. Counting Sort Algorithm20. Heap Sort Basics21. Heap Algorithms22. Heap Properties and Examples23. Heap Operations24. Heap Sort Algorithm Analysis25. Heap Insertion and Deletion26. Tree Based Algorithms and Hashing27. Red Black Tree Basics28. Binary Search Tree Basics29. Tree Searching Algorithms30. Analysis of Tree Searching Algorithms31. Analysis of Insertion and Deletion in BST32. Hashing Basics33. Examples of Hash Functions34. Analysis of Collision Resolution Techniques35. Dynamic Programming36. 0-1 Knapsack Problem37. Fractional Knapsack Problem38. Longest Common Subsequence39. Shortest Path Finding40. Matrix Chain Multiplication41. Assembly Line Chain Problem42. Greedy Algorithms43. Prim's Algorithm44. Kruskal's Algorithm45. Dijkstra's Algorithm46. Huffman Coding47. NP-Completeness48. Polynomial Time Verification49. Reducibility50. NP-Completeness Proofs51. Randomized Algorithms52. Particle Swarm Optimization53. Genetic Algorithms
    COMP3138›Fractional Knapsack Problem
    Design and Analysis of AlgorithmsTopic 37 of 53

    Fractional Knapsack Problem

    7 minread
    1,110words
    Intermediatelevel

    Fractional Knapsack Problem

    The Fractional Knapsack Problem is a variation of the 0/1 knapsack problem, where we can take fractions (or portions) of items, rather than having to decide whether to include or exclude each item entirely. This makes the problem easier to solve because you are allowed to break an item into smaller parts and take just a fraction of its total value or weight, depending on the knapsack's capacity.

    Problem Statement:

    • We are given n items, each with:
      • A value v[i]
      • A weight w[i]
    • We are given a knapsack with a weight capacity W.
    • Our goal is to determine the maximum value that can be obtained by selecting fractions of items such that the total weight does not exceed W.

    Unlike the 0/1 Knapsack Problem, in the fractional version, we can take any fraction of an item, and the value of the fraction will be proportional to the amount of that item taken.

    Greedy Approach:

    The Fractional Knapsack Problem can be solved using a Greedy Algorithm, as it satisfies the greedy-choice property. This means that the locally optimal choice at each step (i.e., picking the most valuable item per unit weight) leads to a globally optimal solution.

    Greedy Strategy:

    1. Compute the value-to-weight ratio for each item:
      For each item i, calculate the ratio v[i] / w[i]. This ratio indicates the value we get per unit of weight.

    2. Sort the items based on the value-to-weight ratio in descending order.

    3. Take the items:

      • Start with the item with the highest value-to-weight ratio.
      • Take as much of this item as possible (up to the knapsack's remaining capacity).
      • If the remaining capacity is less than the item's weight, take the fraction of the item that fits.
    4. Repeat for the next most valuable item until the knapsack is full or all items have been considered.

    Mathematical Formulation:

    Given items i with value v[i] and weight w[i], the value-to-weight ratio is:

    ratio[i] = v[i] / w[i]
    

    To maximize the value, we:

    • Sort the items in descending order of the value-to-weight ratio.
    • Take the fraction of the items that fits in the remaining capacity of the knapsack.

    Steps to Solve:

    1. Compute the value-to-weight ratio for each item.
    2. Sort items based on the value-to-weight ratio.
    3. Iterate over the sorted items, and for each item:
      • If the item can fully fit, take it completely.
      • If the item cannot fully fit, take the fraction that can fit.
    4. Repeat the process until the knapsack is full or all items are processed.

    Example:

    Let's go through an example to better understand the solution.

    Given:

    • Knapsack capacity: W = 50
    • Items with their values and weights:
    Item Weight (w[i]) Value (v[i]) Value-to-Weight Ratio (v[i]/w[i])
    1 10 60 6.0
    2 20 100 5.0
    3 30 120 4.0

    Steps to Solve:

    1. Compute value-to-weight ratios:

      • Item 1: 6010=6.0\frac{60}{10} = 6.01060​=6.0
      • Item 2: 10020=5.0\frac{100}{20} = 5.020100​=5.0
      • Item 3: 12030=4.0\frac{120}{30} = 4.030120​=4.0
    2. Sort the items based on the value-to-weight ratio (in descending order):

      • Item 1: 6.0
      • Item 2: 5.0
      • Item 3: 4.0
    3. Start filling the knapsack:

      • Item 1: Weight = 10, Value = 60, Ratio = 6.0

        • Take the whole item (capacity left = 50 - 10 = 40).
        • Total value = 60.
      • Item 2: Weight = 20, Value = 100, Ratio = 5.0

        • Take the whole item (capacity left = 40 - 20 = 20).
        • Total value = 60 + 100 = 160.
      • Item 3: Weight = 30, Value = 120, Ratio = 4.0

        • The knapsack has only 20 capacity left. Take 20/30 of the item (fraction).
        • Fraction of value = 2030×120=80\frac{20}{30} \times 120 = 803020​×120=80.
        • Total value = 160 + 80 = 240.
    4. Knapsack is full with a total value of 240.

    Greedy Algorithm Implementation in C++:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    // Structure to represent an item
    struct Item {
        int weight;
        int value;
        float ratio;  // Value-to-weight ratio
    };
    
    // Comparison function to sort items by value-to-weight ratio in descending order
    bool compare(Item a, Item b) {
        return a.ratio > b.ratio;
    }
    
    // Function to solve Fractional Knapsack Problem
    float fractionalKnapsack(int W, std::vector<Item>& items) {
        // Sort items by their value-to-weight ratio in descending order
        std::sort(items.begin(), items.end(), compare);
    
        float totalValue = 0.0f;
        for (auto& item : items) {
            if (W == 0) {
                break;
            }
    
            if (item.weight <= W) {
                // If the item can be fully included, take it completely
                totalValue += item.value;
                W -= item.weight;
            } else {
                // Otherwise, take the fraction of the item that fits
                totalValue += item.value * ((float)W / item.weight);
                W = 0;
            }
        }
    
        return totalValue;
    }
    
    int main() {
        int W = 50; // Knapsack capacity
        std::vector<Item> items = {
            {10, 60, 0.0f},  // Item 1
            {20, 100, 0.0f}, // Item 2
            {30, 120, 0.0f}  // Item 3
        };
    
        // Compute the value-to-weight ratio for each item
        for (auto& item : items) {
            item.ratio = (float)item.value / item.weight;
        }
    
        // Calculate the maximum value achievable
        float maxValue = fractionalKnapsack(W, items);
        
        std::cout << "Maximum value in knapsack = " << maxValue << std::endl;
    
        return 0;
    }
    

    Explanation of Code:

    1. Item Structure: We define a structure Item to hold the weight, value, and value-to-weight ratio for each item.
    2. Comparison Function: compare() sorts the items based on the value-to-weight ratio in descending order.
    3. fractionalKnapsack(): This function implements the greedy algorithm to solve the fractional knapsack problem. It iterates through the sorted items and adds the item or its fraction to the knapsack.
    4. Main Function: It initializes the items and computes the maximum value that can be packed into the knapsack.

    Time Complexity:

    • Time Complexity: O(n log n), where n is the number of items, due to sorting the items by the value-to-weight ratio.
    • Space Complexity: O(n), where n is the number of items, for storing the items and their ratios.

    Conclusion:

    • The Fractional Knapsack Problem can be efficiently solved using a greedy approach, where we always pick the item with the highest value-to-weight ratio.
    • Unlike the 0/1 knapsack problem, in the fractional version, we are allowed to take fractional parts of an item, which simplifies the problem and allows for an optimal solution.
    Previous topic 36
    0-1 Knapsack Problem
    Next topic 38
    Longest Common Subsequence

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,110
      Code examples0
      DifficultyIntermediate