Open In App

Fractional Knapsack Problem

Last Updated : 03 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
32.46%
2.9L

Given the weights and profits of N items, in the form of {profit, weight} put these items in a knapsack of capacity W to get the maximum total profit in the knapsack. In Fractional Knapsack, we can break items for maximizing the total value of the knapsack.

Input: arr[] = {{60, 10}, {100, 20}, {120, 30}}, W = 50
Output: 240 
Explanation: By taking items of weight 10 and 20 kg and 2/3 fraction of 30 kg. 
Hence total price will be 60+100+(2/3)(120) = 240

Input:  arr[] = {{500, 30}}, W = 10
Output: 166.667

Recommended Problem

Naive Approach: To solve the problem follow the below idea:

Try all possible subsets with all different fractions.

Time Complexity: O(2N)
Auxiliary Space: O(N)

Fractional Knapsack Problem using Greedy algorithm:

An efficient solution is to use the Greedy approach. 

The basic idea of the greedy approach is to calculate the ratio profit/weight for each item and sort the item on the basis of this ratio. Then take the item with the highest ratio and add them as much as we can (can be the whole element or a fraction of it).

This will always give the maximum profit because, in each step it adds an element such that this is the maximum possible profit for that much weight.

Illustration:

Check the below illustration for a better understanding:

Consider the example: arr[] = {{100, 20}, {60, 10}, {120, 30}}, W = 50.

Sorting: Initially sort the array based on the profit/weight ratio. The sorted array will be {{60, 10}, {100, 20}, {120, 30}}.

Iteration:

  • For i = 0, weight = 10 which is less than W. So add this element in the knapsack. profit = 60 and remaining W = 50 – 10 = 40.
  • For i = 1, weight = 20 which is less than W. So add this element too. profit = 60 + 100 = 160 and remaining W = 40 – 20 = 20.
  • For i = 2, weight = 30 is greater than W. So add 20/30 fraction = 2/3 fraction of the element. Therefore profit = 2/3 * 120 + 160 = 80 + 160 = 240 and remaining W becomes 0.

So the final profit becomes 240 for W = 50.

Follow the given steps to solve the problem using the above approach:

  • Calculate the ratio (profit/weight) for each item.
  • Sort all the items in decreasing order of the ratio.
  • Initialize res = 0, curr_cap = given_cap.
  • Do the following for every item i in the sorted order:
    • If the weight of the current item is less than or equal to the remaining capacity then add the value of that item into the result
    • Else add the current item as much as we can and break out of the loop.
  • Return res.

Below is the implementation of the above approach:

C++




// C++ program to solve fractional Knapsack Problem
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure for an item which stores weight and
// corresponding value of Item
struct Item {
    int profit, weight;
 
    // Constructor
    Item(int profit, int weight)
    {
        this->profit = profit;
        this->weight = weight;
    }
};
 
// Comparison function to sort Item
// according to profit/weight ratio
static bool cmp(struct Item a, struct Item b)
{
    double r1 = (double)a.profit / (double)a.weight;
    double r2 = (double)b.profit / (double)b.weight;
    return r1 > r2;
}
 
// Main greedy function to solve problem
double fractionalKnapsack(int W, struct Item arr[], int N)
{
    // Sorting Item on basis of ratio
    sort(arr, arr + N, cmp);
 
    double finalvalue = 0.0;
 
    // Looping through all items
    for (int i = 0; i < N; i++) {
         
        // If adding Item won't overflow,
        // add it completely
        if (arr[i].weight <= W) {
            W -= arr[i].weight;
            finalvalue += arr[i].profit;
        }
 
        // If we can't add current Item,
        // add fractional part of it
        else {
            finalvalue
                += arr[i].profit
                   * ((double)W / (double)arr[i].weight);
            break;
        }
    }
 
    // Returning final value
    return finalvalue;
}
 
// Driver code
int main()
{
    int W = 50;
    Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << fractionalKnapsack(W, arr, N);
    return 0;
}


Java




// Java program to solve fractional Knapsack Problem
 
import java.lang.*;
import java.util.Arrays;
import java.util.Comparator;
 
// Greedy approach
public class FractionalKnapSack {
     
    // Function to get maximum value
    private static double getMaxValue(ItemValue[] arr,
                                      int capacity)
    {
        // Sorting items by profit/weight ratio;
        Arrays.sort(arr, new Comparator<ItemValue>() {
            @Override
            public int compare(ItemValue item1,
                               ItemValue item2)
            {
                double cpr1
                    = new Double((double)item1.profit
                                 / (double)item1.weight);
                double cpr2
                    = new Double((double)item2.profit
                                 / (double)item2.weight);
 
                if (cpr1 < cpr2)
                    return 1;
                else
                    return -1;
            }
        });
 
        double totalValue = 0d;
 
        for (ItemValue i : arr) {
 
            int curWt = (int)i.weight;
            int curVal = (int)i.profit;
 
            if (capacity - curWt >= 0) {
 
                // This weight can be picked whole
                capacity = capacity - curWt;
                totalValue += curVal;
            }
            else {
 
                // Item cant be picked whole
                double fraction
                    = ((double)capacity / (double)curWt);
                totalValue += (curVal * fraction);
                capacity
                    = (int)(capacity - (curWt * fraction));
                break;
            }
        }
 
        return totalValue;
    }
 
    // Item value class
    static class ItemValue {
 
        int profit, weight;
 
        // Item value function
        public ItemValue(int val, int wt)
        {
            this.weight = wt;
            this.profit = val;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        ItemValue[] arr = { new ItemValue(60, 10),
                            new ItemValue(100, 20),
                            new ItemValue(120, 30) };
 
        int capacity = 50;
 
        double maxValue = getMaxValue(arr, capacity);
 
        // Function call
        System.out.println(maxValue);
    }
}


Python3




# Structure for an item which stores weight and
# corresponding value of Item
class Item:
    def __init__(self, profit, weight):
        self.profit = profit
        self.weight = weight
 
# Main greedy function to solve problem
def fractionalKnapsack(W, arr):
 
    # Sorting Item on basis of ratio
    arr.sort(key=lambda x: (x.profit/x.weight), reverse=True)   
 
    # Result(value in Knapsack)
    finalvalue = 0.0
 
    # Looping through all Items
    for item in arr:
 
        # If adding Item won't overflow,
        # add it completely
        if item.weight <= W:
            W -= item.weight
            finalvalue += item.profit
 
        # If we can't add current Item,
        # add fractional part of it
        else:
            finalvalue += item.profit * W / item.weight
            break
     
    # Returning final value
    return finalvalue
 
 
# Driver Code
if __name__ == "__main__":
    W = 50
    arr = [Item(60, 10), Item(100, 20), Item(120, 30)]
 
    # Function call
    max_val = fractionalKnapsack(W, arr)
    print(max_val)


C#




// C# program to solve fractional Knapsack Problem
 
using System;
using System.Collections;
 
class GFG {
 
    // Class for an item which stores weight and
    // corresponding value of Item
    class item {
        public int profit;
        public int weight;
 
        public item(int profit, int weight)
        {
            this.profit = profit;
            this.weight = weight;
        }
    }
 
    // Comparison function to sort Item according
    // to val/weight ratio
    class cprCompare : IComparer {
        public int Compare(Object x, Object y)
        {
            item item1 = (item)x;
            item item2 = (item)y;
            double cpr1 = (double)item1.profit
                          / (double)item1.weight;
            double cpr2 = (double)item2.profit
                          / (double)item2.weight;
 
            if (cpr1 < cpr2)
                return 1;
 
            return cpr1 > cpr2 ? -1 : 0;
        }
    }
 
    // Main greedy function to solve problem
    static double FracKnapSack(item[] items, int w)
    {
 
        // Sort items based on cost per units
        cprCompare cmp = new cprCompare();
        Array.Sort(items, cmp);
 
        // Traverse items, if it can fit,
        // take it all, else take fraction
        double totalVal = 0f;
        int currW = 0;
 
        foreach(item i in items)
        {
            float remaining = w - currW;
 
            // If the whole item can be
            // taken, take it
            if (i.weight <= remaining) {
                totalVal += (double)i.profit;
                currW += i.weight;
            }
 
            // dd fraction until we run out of space
            else {
                if (remaining == 0)
                    break;
 
                double fraction
                    = remaining / (double)i.weight;
                totalVal += fraction * (double)i.profit;
                currW += (int)(fraction * (double)i.weight);
            }
        }
        return totalVal;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int W = 50;
        item[] arr = { new item(60, 10), new item(100, 20),
                       new item(120, 30) };
 
        // Function call
        Console.WriteLine(FracKnapSack(arr, W));
    }
}
 
// This code is contributed by Mohamed Adel


Javascript




// JavaScript program to solve fractional Knapsack Problem
 
// Structure for an item which stores weight and
// corresponding value of Item
class Item {
    constructor(profit, weight) {
        this.profit = profit;
        this.weight = weight;
    }
}
 
// Comparison function to sort Item
// according to val/weight ratio
function cmp(a, b) {
    let r1 = a.profit / a.weight;
    let r2 = b.profit / b.weight;
    return r1 > r2;
}
 
// Main greedy function to solve problem
function fractionalKnapsack(W, arr) {
    // Sorting Item on basis of ratio
    arr.sort(cmp);
 
    let finalvalue = 0.0;
 
    // Looping through all items
    for (let i = 0; i < arr.length; i++) {
         
        // If adding Item won't overflow,
        // add it completely
        if (arr[i].weight <= W) {
            W -= arr[i].weight;
            finalvalue += arr[i].profit;
        }
 
        // If we can't add current Item,
        // add fractional part of it
        else {
            finalvalue += arr[i].profit * (W / arr[i].weight);
            break;
        }
    }
 
    // Returning final value
    return finalvalue;
}
 
// Driver code
let W = 50;
let arr = [new Item(60, 10), new Item(100, 20), new Item(120, 30)];
 
console.log(fractionalKnapsack(W, arr));
 
// This code is contributed by lokeshpotta20


Output

240

Time Complexity: O(N * logN)
Auxiliary Space: O(N)



Previous Article
Next Article

Similar Reads

Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Fractional Knapsack Queries
Given an integer array, consisting of positive weights "W" and their values "V" respectively as a pair and some queries consisting of an integer 'C' specifying the capacity of the knapsack, find the maximum value of products that can be put in the knapsack if the breaking of items is allowed. Examples: Input: arr[] = { {1, 2}, {1, 3}, {3, 7} }, q =
9 min read
Unbounded Fractional Knapsack
Given the weights and values of n items, the task is to put these items in a knapsack of capacity W to get the maximum total value in the knapsack, we can repeatedly put the same item and we can also put a fraction of an item. Examples: Input: val[] = {14, 27, 44, 19}, wt[] = {6, 7, 9, 8}, W = 50 Output: 244.444 Input: val[] = {100, 60, 120}, wt[]
5 min read
Fractional Knapsack in Python
Given the weights and profits of N items, in the form of {profit, weight} put these items in a knapsack of capacity W to get the maximum total profit in the knapsack. In Fractional Knapsack, we can break items for maximizing the total value of the knapsack. Examples: Input: arr[] = {{60, 10}, {100, 20}, {120, 30}}, W = 50Output: 240 Explanation: By
5 min read
Difference Between Greedy Knapsack and 0/1 Knapsack Algorithms
The 0/1 Knapsack algorithm is a dynamic programming approach where items are either completely included or not at all. It considers all combinations to find the maximum total value. On the other hand, the Greedy Knapsack algorithm, also known as the Fractional Knapsack, allows for items to be broken into fractions, selecting items with the highest
9 min read
0/1 Knapsack Problem to print all possible solutions
Given weights and profits of N items, put these items in a knapsack of capacity W. The task is to print all possible solutions to the problem in such a way that there are no remaining items left whose weight is less than the remaining capacity of the knapsack. Also, compute the maximum profit.Examples: Input: Profits[] = {60, 100, 120, 50} Weights[
10 min read
Crossword Puzzle Of The Week #20 (KnapSack Problem)
In this issue of Crossword Puzzle of the Week, we will dive into the topic of the Knapsack Problem. The solution to the crossword puzzle is provided at the end. HINTS:Across: 1. In _____ Knapsack, we can break items for maximizing the total value of the knapsack. 2. 0/1 Knapsack problem has both properties (Overlapping Subproblem and Optimal Substr
2 min read
GFact | Why doesn't Greedy Algorithm work for 0-1 Knapsack problem?
In this article, we will discuss why the 0-1 knapsack problem cannot be solved by the greedy method, or why the greedy algorithm is not optimal for the 0-1 Knapsack Problem. Greedy algorithms are widely used in optimization problems, where the goal is to find the best solution from a set of choices. The greedy approach makes locally optimal choices
2 min read
A Space Optimized DP solution for 0-1 Knapsack Problem
Given the weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the max
15+ min read
Extended Knapsack Problem
Given N items, each item having a given weight Ci and a profit value Pi, the task is to maximize the profit by selecting a maximum of K items adding up to a maximum weight W. Examples: Input: N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 8, K = 2. Output: 12 Explanation: Here, the maximum possible profit is when we take 2 items: item2 (P
12 min read
0/1 Knapsack Problem
Prerequisites: Introduction to Knapsack Problem, its Types and How to solve them Given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum
15+ min read
Introduction to Knapsack Problem, its Types and How to solve them
The Knapsack problem is an example of the combinational optimization problem. This problem is also commonly known as the "Rucksack Problem". The name of the problem is defined from the maximization problem as mentioned below: Given a bag with maximum weight capacity of W and a set of items, each having a weight and a value associated with it. Decid
6 min read
Sort given Array based on the fractional values
Given an array arr[] that contains N real numbers. The task is to sort the array in decreasing order of the Fractional Values Note: If the values of the fractional part are same then sort those elements in Decreasing order of their Integer Values. Examples: Input: arr[] = { 8.33, -3.85, 1.999, 6.33, 5}Output: { 1.999, 8.33, 6.33, -3.85 , 5}Explanat
10 min read
Find the fractional (or n/k - th) node in linked list
Given a singly linked list and a number k, write a function to find the (n/k)-th element, where n is the number of elements in the list. We need to consider ceil value in case of decimals. Examples: Input : list = 1->2->3->4->5->6 k = 2 Output : 3 Since n = 6 and k = 2, we print (6/2)-th node which is 3. Input : list = 2->7->9-
7 min read
Printing Items in 0/1 Knapsack
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the items such t
12 min read
Knapsack with large Weights
Given a knapsack with capacity C and two arrays w[] and val[] representing the weights and values of N distinct items, the task is to find the maximum value you can put into the knapsack. Items cannot be broken and an item with weight X takes X capacity of the knapsack. Examples: Input: w[] = {3, 4, 5}, val[] = {30, 50, 60}, C = 8 Output: 90 We tak
13 min read
Maximum sum of values of N items in 0-1 Knapsack by reducing weight of at most K items in half
Given weights and values of N items and the capacity W of the knapsack. Also given that the weight of at most K items can be changed to half of its original weight. The task is to find the maximum sum of values of N items that can be obtained such that the sum of weights of items in knapsack does not exceed the given capacity W. Examples: Input: W
15+ min read
Double Knapsack | Dynamic Programming
Given an array 'arr' containing the weight of 'N' distinct items, and two knapsacks that can withstand 'W1' and 'W2' weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e an item should be put in one of the bags as a whole.Examples: Input
15+ min read
0-1 knapsack queries
Given an integer array W[] consisting of weights of the items and some queries consisting of capacity C of knapsack, for each query find maximum weight we can put in the knapsack. Value of C doesn't exceed a certain integer C_MAX. Examples: Input: W[] = {3, 8, 9} q = {11, 10, 4} Output: 11 9 3 If C = 11: select 3 + 8 = 11 If C = 10: select 9 If C =
12 min read
POTD Solutions | 25 Oct’ 23 | Knapsack with Duplicate Items
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Dynamic Programming but will also help you build up problem-solving skills. We recommend you to try this
9 min read
Implementation of 0/1 Knapsack using Branch and Bound
Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity Cap(W). Note: The constraint here is we can either put an item completely into the bag or cannot p
15+ min read
Approximation algorithms for Knapsack
Knapsack problems are those problems in which some set of items will be given to us, each with a weight and value and we will be asked to find the most valuable combination by maximizing the total value of items and the weight should not exceed the knapsack weigh. Approximation Algorithms: It plays a vital role in finding the optimal solution to th
13 min read
0/1 Knapsack using Least Cost Branch and Bound
Given N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that:   The sum of weights taken into the knapsack is less than or equal to C.The sum of values of the items in the knapsack is maximum among all the possible combinations.Examples:   Input: N = 4, C = 15, V[]= {10, 10, 12, 18}, W[]= {2, 4,
15+ min read
Unbounded Knapsack in Python
Given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity, the task is to determine the maximum value that can be obtained by putting items into the knapsack. In the Unbounded Knapsack problem, you can use each item as many times as you want. Example: Input: Weights: [1, 3, 4, 5], Values: [10, 40, 50, 70],
2 min read
Unbounded Knapsack (Repetition of items allowed) | Efficient Approach
Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W. Note: Each weight can be included multiple times. Examples: Input: W = 4, val[] = {6, 18}, wt[] = {2, 3}Output: 18Explanation: The maximum value
8 min read
0/1 Knapsack using Branch and Bound
Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity W. Note: The constraint here is we can either put an item completely into the bag or cannot put it
15+ min read
Unbounded Knapsack (Repetition of items allowed)
Given a knapsack weight W and a set of n items with certain value vali and weight wti, we need to calculate the maximum amount that could make up this quantity exactly. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item. Note: N is always positive i.e greater than zero Examples: In
15+ min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg