The Wayback Machine - https://web.archive.org/web/20240811054052/https://www.geeksforgeeks.org/unbounded-fractional-knapsack/
Open In App

Unbounded Fractional Knapsack

Last Updated : 14 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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[] = {20, 10, 30}, W = 50 
Output: 300 

Approach: The idea here is to just find the item which has the largest value to weight ratio. Then fill the whole knapsack with this item only, in order to maximize the final value of the knapsack.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximum required value
float knapSack(int W, float wt[], float val[], int n)
{
 
    // maxratio will store the maximum value to weight
    // ratio we can have for any item and maxindex
    // will store the index of that element
    float maxratio = INT_MIN;
    int maxindex = 0;
 
    // Find the maximum ratio
    for (int i = 0; i < n; i++) {
        if ((val[i] / wt[i]) > maxratio) {
            maxratio = (val[i] / wt[i]);
            maxindex = i;
        }
    }
 
    // The item with the maximum value to
    // weight ratio will be put into
    // the knapsack repeatedly until full
    return (W * maxratio);
}
 
// Driver code
int main()
{
    float val[] = { 14, 27, 44, 19 };
    float wt[] = { 6, 7, 9, 8 };
    int n = sizeof(val) / sizeof(val[0]);
    int W = 50;
 
    cout << knapSack(W, wt, val, n);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
 
    // Function to return the maximum required value
    static float knapSack(int W, float wt[],
                            float val[], int n)
    {
 
        // maxratio will store the maximum value to weight
        // ratio we can have for any item and maxindex
        // will store the index of that element
        float maxratio = Integer.MIN_VALUE;
        int maxindex = 0;
 
        // Find the maximum ratio
        for (int i = 0; i < n; i++)
        {
            if ((val[i] / wt[i]) > maxratio)
            {
                maxratio = (val[i] / wt[i]);
                maxindex = i;
            }
        }
 
        // The item with the maximum value to
        // weight ratio will be put into
        // the knapsack repeatedly until full
        return (W * maxratio);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        float val[] = {14, 27, 44, 19};
        float wt[] = {6, 7, 9, 8};
        int n = val.length;
        int W = 50;
 
        System.out.println(knapSack(W, wt, val, n));
    }
}
 
// This code is contributed by 29AjayKumar


Python3




# Python implementation of the approach
 
import sys
 
# Function to return the maximum required value
def knapSack(W, wt, val, n):
 
    # maxratio will store the maximum value to weight
    # ratio we can have for any item and maxindex
    # will store the index of that element
    maxratio = -sys.maxsize-1;
    maxindex = 0;
 
    # Find the maximum ratio
    for i in range(n):
        if ((val[i] / wt[i]) > maxratio):
            maxratio = (val[i] / wt[i]);
            maxindex = i;
 
 
    # The item with the maximum value to
    # weight ratio will be put into
    # the knapsack repeatedly until full
    return (W * maxratio);
 
 
# Driver code
 
val = [ 14, 27, 44, 19 ];
wt = [ 6, 7, 9, 8 ];
n = len(val);
W = 50;
 
print(knapSack(W, wt, val, n));
 
# This code is contributed by Rajput-Ji


C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the maximum required value
    static float knapSack(int W, float []wt,
                            float []val, int n)
    {
 
        // maxratio will store the maximum value to weight
        // ratio we can have for any item and maxindex
        // will store the index of that element
        float maxratio = int.MinValue;
        int maxindex = 0;
 
        // Find the maximum ratio
        for (int i = 0; i < n; i++)
        {
            if ((val[i] / wt[i]) > maxratio)
            {
                maxratio = (val[i] / wt[i]);
                maxindex = i;
            }
        }
 
        // The item with the maximum value to
        // weight ratio will be put into
        // the knapsack repeatedly until full
        return (W * maxratio);
    }
 
    // Driver code
    public static void Main()
    {
        float []val = {14, 27, 44, 19};
        float []wt = {6, 7, 9, 8};
        int n = val.Length;
        int W = 50;
 
        Console.WriteLine(knapSack(W, wt, val, n));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the maximum required value
function knapSack(W, wt, val, n)
{
 
    // maxratio will store the maximum value to weight
    // ratio we can have for any item and maxindex
    // will store the index of that element
    var maxratio = -1000000000;
    var maxindex = 0;
 
    // Find the maximum ratio
    for (var i = 0; i < n; i++) {
        if (parseInt(val[i] / wt[i]) > maxratio) {
            maxratio = (val[i] / wt[i]);
            maxindex = i;
        }
    }
 
    // The item with the maximum value to
    // weight ratio will be put into
    // the knapsack repeatedly until full
    return (W * maxratio);
}
 
// Driver code
var val = [14, 27, 44, 19];
var wt = [6, 7, 9, 8];
var n = val.length;
var W = 50;
document.write( knapSack(W, wt, val, n).toFixed(3));
 
</script>


Output: 

244.444

 

Time Complexity: O(n) where n is size of input array val and wt. This is because a for loop is being executed from 1 till n in knapSack function.

Space Complexity: O(1) as no extra space has been used.



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
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)
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
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
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
Fractional Knapsack Problem
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 = 50Output: 240 Explanation: By taking it
8 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
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes positive for the first time. Since f() is monotonic
11 min read
Largest area in a grid unbounded by towers
Given two integers L and W representing the dimensions of a grid, and two arrays X[] and Y[] of length N denoting the number of towers present on the grid at positions (X[i], Y[i]), where (0 &lt;= i &lt;= N - 1). The task is to find the largest unbounded area in the field which is not defended by the towers. Examples: Input: L = 15, W = 8, N = 3 X[
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg