Search⌘ K

Solution: Fractional Knapsack Problem

Explore the greedy approach to solving the fractional knapsack problem by understanding how to maximize total value through value-to-weight ratios. This lesson helps you compare the brute force and greedy methods, focusing on implementing an efficient solution with O(n log n) time complexity, crucial for coding interviews.

Solution #1: Brute Force

C++
#include "HelperFunctions.h"
double fractionalKnapsack(int knapsackWeight, struct Item itemArray[], int n) {
int currentWeight = 0; // Current weight in knapsack
double finalvalue = 0.0; // Result (value in Knapsack)
double tempValue = 0.0;
// compute all combinations
int * combination = new int[n];
for (int i = 0; i < n; i++) {
combination[i] = i;
}
std::sort(combination, combination + n);
// find value for all combinations
do {
for (int i = 0; i < n; i++) {
// If adding Item won't overflow, add it completely
if (currentWeight + itemArray[combination[i]].weight <= knapsackWeight) {
currentWeight += itemArray[combination[i]].weight;
tempValue += itemArray[combination[i]].value;
}
// If we can't add current Item, add fractional part of it
else {
int remain = knapsackWeight - currentWeight;
tempValue += itemArray[combination[i]].value * ((double) remain / itemArray[combination[i]].weight);
}
}
// save only the maximum value
if (finalvalue < tempValue)
finalvalue = tempValue;
tempValue = 0.0;
currentWeight = 0;
} while (std::next_permutation(combination, combination + 3)); // produces all combinations
delete combination;
return finalvalue;
}
int main() {
int knapsackWeight = 50;
Item itemArray[] = {{120, 30}, {100, 20}, {60, 10}};
int n = sizeof(itemArray) / sizeof(itemArray[0]);
cout << "Maximum value we can obtain = ";
cout << fractionalKnapsack(knapsackWeight, itemArray, n);
return 0;
}

We can solve this problem using the brute force method. However, trying all possible subsets with all different fractions will take too much time.

Such an answer is very naive and in no way suitable for an interview. We are looking for a more optimized solution.

Time Complexity

The time complexity will be O(2n)O(2^n) ...