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.444Input: 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>usingnamespacestd;// Function to return the maximum required valuefloatknapSack(intW, floatwt[], floatval[], intn){    // maxratio will store the maximum value to weight    // ratio we can have for any item and maxindex    // will store the index of that element    floatmaxratio = INT_MIN;    intmaxindex = 0;    // Find the maximum ratio    for(inti = 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 codeintmain(){    floatval[] = { 14, 27, 44, 19 };    floatwt[] = { 6, 7, 9, 8 };    intn = sizeof(val) / sizeof(val[0]);    intW = 50;    cout << knapSack(W, wt, val, n);    return0;} | 
Java
| // Java implementation of the approachclassGFG {    // Function to return the maximum required value    staticfloatknapSack(intW, floatwt[],                             floatval[], intn)     {        // maxratio will store the maximum value to weight        // ratio we can have for any item and maxindex        // will store the index of that element        floatmaxratio = Integer.MIN_VALUE;        intmaxindex = 0;        // Find the maximum ratio        for(inti = 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    publicstaticvoidmain(String[] args)     {        floatval[] = {14, 27, 44, 19};        floatwt[] = {6, 7, 9, 8};        intn = val.length;        intW = 50;        System.out.println(knapSack(W, wt, val, n));    }}// This code is contributed by 29AjayKumar | 
Python3
| # Python implementation of the approachimportsys # Function to return the maximum required valuedefknapSack(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    fori inrange(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 codeval =[ 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 approachusingSystem;classGFG {    // Function to return the maximum required value    staticfloatknapSack(intW, float[]wt,                             float[]val, intn)     {        // maxratio will store the maximum value to weight        // ratio we can have for any item and maxindex        // will store the index of that element        floatmaxratio = int.MinValue;        intmaxindex = 0;        // Find the maximum ratio        for(inti = 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    publicstaticvoidMain()     {        float[]val = {14, 27, 44, 19};        float[]wt = {6, 7, 9, 8};        intn = val.Length;        intW = 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 valuefunctionknapSack(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    varmaxratio = -1000000000;    varmaxindex = 0;    // Find the maximum ratio    for(vari = 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 codevarval = [14, 27, 44, 19];varwt = [6, 7, 9, 8];varn = val.length;varW = 50;document.write( knapSack(W, wt, val, n).toFixed(3));</script> | 
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







