Fractional Knapsack Problem
Last Updated :
23 Jul, 2025
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:
- Calculate the ratio (profit/weight) for each item.
- Sort all the items in decreasing order of the ratio.
- Initialize res = 0, current capacity= given capacity.
- 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++ 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));
Time Complexity: O(n Log n)
Auxiliary Space: O(n)
Fractional Knapsack Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem