The Wayback Machine - https://web.archive.org/web/20250803140058/https://www.geeksforgeeks.org/dsa/fractional-knapsack-problem/
Open In App

Fractional Knapsack Problem

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays, val[] and wt[], representing the values and weights of items, and an integer capacity representing the maximum weight a knapsack can hold, the task is to determine the maximum total value that can be achieved by putting items in the knapsack. You are allowed to break items into fractions if necessary.

Note: Return the maximum value as a double, rounded to 6 decimal places.

Examples:

Input: val[] = [60, 100, 120], wt[] = [10, 20, 30], capacity = 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:  val[] = [500], wt[] = [30], capacity = 10
Output: 166.667

Approach:

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: val[] = [60, 100, 120], wt[] = [10, 20, 30], capacity = 50. Store the value and weight of each item in form {value, weight}. items[] = {{60, 10}, {100, 20}, {120, 30}}.

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

So the final profit becomes 240 for capacity = 50.

Step by step approach:

  1. Calculate the ratio (profit/weight) for each item.
  2. Sort all the items in decreasing order of the ratio.
  3. Initialize res = 0, current capacity= given capacity.
  4. 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.
  5. Return res.

Below is the implementation of the above approach:

C++
// C++ code to implement Fractional Knapsack Problem
#include <bits/stdc++.h>
using namespace std;

// Comparison function to sort items based on value/weight ratio
bool compare(vector<int>& a, vector<int>& b) {
    double a1 = (1.0 * a[0]) / a[1];
    double b1 = (1.0 * b[0]) / b[1];
    return a1 > b1;
}

double fractionalKnapsack(vector<int>& val, vector<int>& wt, int capacity) {
    int n = val.size();
    
    // Create 2D vector to store value and weight
    // items[i][0] = value, items[i][1] = weight
    vector<vector<int>> items(n, vector<int>(2));
    
    for (int i = 0; i < n; i++) {
        items[i][0] = val[i];
        items[i][1] = wt[i];
    }
    
    // Sort items based on value-to-weight ratio in descending order
    sort(items.begin(), items.end(), compare);
    
    double res = 0.0;
    int currentCapacity = capacity;
    
    // Process items in sorted order
    for (int i = 0; i < n; i++) {
        
        // If we can take the entire item
        if (items[i][1] <= currentCapacity) {
            res += items[i][0];
            currentCapacity -= items[i][1];
        }
        
        // Otherwise take a fraction of the item
        else {
            res += (1.0 * items[i][0] / items[i][1]) * currentCapacity;
            
            // Knapsack is full
            break; 
        }
    }
    
    return res;
}

int main() {
    vector<int> val = {60, 100, 120};
    vector<int> wt = {10, 20, 30};
    int capacity = 50;
    
    cout << fractionalKnapsack(val, wt, capacity) << endl;
    
    return 0;
}
Java
// Java program to solve fractional Knapsack Problem

import java.util.*;

class GfG {

    // Comparison function to sort items based on value/weight ratio
    static class ItemComparator implements Comparator<int[]> {
        public int compare(int[] a, int[] b) {
            double a1 = (1.0 * a[0]) / a[1];
            double b1 = (1.0 * b[0]) / b[1];
            return Double.compare(b1, a1);
        }
    }

    static double fractionalKnapsack(int[] val, int[] wt, int capacity) {
        int n = val.length;

        // Create 2D array to store value and weight
        // items[i][0] = value, items[i][1] = weight
        int[][] items = new int[n][2];

        for (int i = 0; i < n; i++) {
            items[i][0] = val[i];
            items[i][1] = wt[i];
        }

        // Sort items based on value-to-weight ratio in descending order
        Arrays.sort(items, new ItemComparator());

        double res = 0.0;
        int currentCapacity = capacity;

        // Process items in sorted order
        for (int i = 0; i < n; i++) {

            // If we can take the entire item
            if (items[i][1] <= currentCapacity) {
                res += items[i][0];
                currentCapacity -= items[i][1];
            }

            // Otherwise take a fraction of the item
            else {
                res += (1.0 * items[i][0] / items[i][1]) * currentCapacity;

                // Knapsack is full
                break;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] val = {60, 100, 120};
        int[] wt = {10, 20, 30};
        int capacity = 50;

        System.out.println(fractionalKnapsack(val, wt, capacity));
    }
}
Python
# Python code to implement Fractional Knapsack Problem
from typing import List

# Comparison function to sort items based on value/weight ratio
def compare(a, b):
    a1 = (1.0 * a[0]) / a[1]
    b1 = (1.0 * b[0]) / b[1]
    return b1 - a1

def fractionalKnapsack(val, wt, capacity):
    n = len(val)

    # Create list to store value and weight
    # items[i][0] = value, items[i][1] = weight
    items = [[val[i], wt[i]] for i in range(n)]

    # Sort items based on value-to-weight ratio in descending order
    items.sort(key=lambda x: x[0]/x[1], reverse=True)

    res = 0.0
    currentCapacity = capacity

    # Process items in sorted order
    for i in range(n):

        # If we can take the entire item
        if items[i][1] <= currentCapacity:
            res += items[i][0]
            currentCapacity -= items[i][1]

        # Otherwise take a fraction of the item
        else:
            res += (1.0 * items[i][0] / items[i][1]) * currentCapacity

            # Knapsack is full
            break

    return res

if __name__ == "__main__":
    val = [60, 100, 120]
    wt = [10, 20, 30]
    capacity = 50

    print(fractionalKnapsack(val, wt, capacity))
C#
// C# program to solve fractional Knapsack Problem
using System;
using System.Collections.Generic;

class GfG {

    // Comparison function to sort items based on value/weight ratio
    class ItemComparer : IComparer<int[]> {
        public int Compare(int[] a, int[] b) {
            double a1 = (1.0 * a[0]) / a[1];
            double b1 = (1.0 * b[0]) / b[1];
            return b1.CompareTo(a1);
        }
    }

    static double fractionalKnapsack(int[] val, int[] wt, int capacity) {
        int n = val.Length;

        // Create 2D array to store value and weight
        // items[i][0] = value, items[i][1] = weight
        int[][] items = new int[n][];
        for (int i = 0; i < n; i++) {
            items[i] = new int[2];
            items[i][0] = val[i];
            items[i][1] = wt[i];
        }

        // Sort items based on value-to-weight ratio in descending order
        Array.Sort(items, new ItemComparer());

        double res = 0.0;
        int currentCapacity = capacity;

        // Process items in sorted order
        for (int i = 0; i < n; i++) {

            // If we can take the entire item
            if (items[i][1] <= currentCapacity) {
                res += items[i][0];
                currentCapacity -= items[i][1];
            }

            // Otherwise take a fraction of the item
            else {
                res += (1.0 * items[i][0] / items[i][1]) * currentCapacity;

                // Knapsack is full
                break;
            }
        }

        return res;
    }

    static void Main() {
        int[] val = {60, 100, 120};
        int[] wt = {10, 20, 30};
        int capacity = 50;

        Console.WriteLine(fractionalKnapsack(val, wt, capacity));
    }
}
JavaScript
// JavaScript program to solve fractional Knapsack Problem

// Comparison function to sort items based on value/weight ratio
function compare(a, b) {
    let a1 = (1.0 * a[0]) / a[1];
    let b1 = (1.0 * b[0]) / b[1];
    return b1 - a1;
}

function fractionalKnapsack(val, wt, capacity) {
    let n = val.length;

    // Create array to store value and weight
    // items[i][0] = value, items[i][1] = weight
    let items = [];
    for (let i = 0; i < n; i++) {
        items.push([val[i], wt[i]]);
    }

    // Sort items based on value-to-weight ratio in descending order
    items.sort(compare);

    let res = 0.0;
    let currentCapacity = capacity;

    // Process items in sorted order
    for (let i = 0; i < n; i++) {

        // If we can take the entire item
        if (items[i][1] <= currentCapacity) {
            res += items[i][0];
            currentCapacity -= items[i][1];
        }

        // Otherwise take a fraction of the item
        else {
            res += (1.0 * items[i][0] / items[i][1]) * currentCapacity;

            // Knapsack is full
            break;
        }
    }

    return res;
}

let val = [60, 100, 120];
let wt = [10, 20, 30];
let capacity = 50;

console.log(fractionalKnapsack(val, wt, capacity));

Output
240

Time Complexity: O(n Log n)
Auxiliary Space: O(n)


Fractional Knapsack Problem
Article Tags :
Practice Tags :

Similar Reads