701365. Fractional Knapsack

Medium

Fractional Knapsack

Slug: fractional-knapsack-1587115620

Difficulty: Medium

Id: 701365

Topic Tags: Greedy, Algorithms

Company Tags: Microsoft

Summary

The Fractional Knapsack problem is a classic greedy algorithm problem that involves selecting items of different weights and values to maximize the total value while staying within a certain weight constraint. The problem requires us to find an optimal subset of items such that the sum of their individual values is maximum, given that the total weight of the selected items does not exceed the capacity of the knapsack.

Detailed Explanation

The Fractional Knapsack problem can be solved using a greedy algorithm. The basic idea is to sort the items based on their value-to-weight ratio (i.e., value / weight) in descending order. Then, we iterate through the sorted list and select the items one by one until the knapsack's capacity is reached or all items have been considered.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty list to store the selected items.
  2. Sort the given items based on their value-to-weight ratio in descending order.
  3. Iterate through the sorted list and consider each item one by one:
    • If the total weight of the selected items plus the weight of the current item does not exceed the knapsack's capacity, add the item to the selected list and update the total weight.
    • Otherwise, calculate the fraction of the item that can be included in the knapsack (i.e., the remaining capacity divided by the item's weight) and add this fraction to the total value of the selected items.
  4. Return the selected list of items as the optimal solution.

The time complexity of this algorithm is O(n log n), where n is the number of items, due to the sorting step. The space complexity is O(1), since we only need a constant amount of space to store the selected items and temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public class FractionalKnapsack {
    public static double fractionalKnapsack(double[] weights, double[] values, int W) {
        double maxVal = 0.0;
        for (int i = 0; i < weights.length; i++) {
            if ((weights[i] / values[i]) > (W / (values[i] - maxVal))) {
                W -= Math.floor((double) (W / (values[i] - maxVal)) * values[i]);
                maxVal += values[i];
            } else {
                W -= weights[i];
                maxVal += values[i];
                break;
            }
        }
        return maxVal;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.