AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsGreedyFractional Knapsack
Greedyintermediategreedyknapsackratio-sort

Fractional Knapsack

The Fractional Knapsack problem allows taking fractions of items unlike the 0/1 variant. The greedy solution is optimal: sort items by value/weight ratio descending, and greedily fill the knapsack with as much of the highest-ratio item as possible, then the next, and so on. O(n log n) due to sorting.

Complexity

Best
O(n log n)
Average
O(n log n)
Worst
O(n log n)
Space
O(1)

Implementation

double fractionalKnapsack(vector<int>& w, vector<int>& v, int W) {
    int n=w.size();
    vector<pair<double,int>> items(n);
    for(int i=0;i<n;i++) items[i]={v[i]/(double)w[i],i};
    sort(items.rbegin(),items.rend());
    double total=0; int rem=W;
    for(auto[ratio,i]:items){
        if(rem==0)break;
        int take=min(w[i],rem);
        total+=take*ratio; rem-=take;
    }
    return total;
}

How It Works

1.Greedy by Ratio

Sort items by value/weight ratio in descending order. Take as much as possible of the highest-ratio item. This maximizes value per unit of capacity used.

2.Why Greedy Works Here

Unlike 0/1 Knapsack (where DP is needed), fractional knapsack allows greedy because partial items are allowed. There is no combinatorial choice — just fill optimally ratio by ratio.

3.vs 0/1 Knapsack

Fractional knapsack is O(n log n) with greedy. 0/1 Knapsack requires O(nW) DP because you cannot take fractions. The fractional solution is always >= the 0/1 solution for the same instance.

Related Algorithms

LayoutGrid0/1 KnapsackTrendingUpActivity SelectionTrendingUpHuffman Encoding

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms