Solution: Fractional Knapsack Problem
This review provides a detailed analysis of the solution to the fractional knapsack problem.
We'll cover the following...
Solution #1: Brute Force
Press + to interact
main.cpp
HelperFunctions.cpp
HelperFunctions.h
#include "HelperFunctions.h"double fractionalKnapsack(int knapsackWeight, struct Item itemArray[], int n) {int currentWeight = 0; // Current weight in knapsackdouble finalvalue = 0.0; // Result (value in Knapsack)double tempValue = 0.0;// compute all combinationsint * combination = new int[n];for (int i = 0; i < n; i++) {combination[i] = i;}std::sort(combination, combination + n);// find value for all combinationsdo {for (int i = 0; i < n; i++) {// If adding Item won't overflow, add it completelyif (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 itelse {int remain = knapsackWeight - currentWeight;tempValue += itemArray[combination[i]].value * ((double) remain / itemArray[combination[i]].weight);}}// save only the maximum valueif (finalvalue < tempValue)finalvalue = tempValue;tempValue = 0.0;currentWeight = 0;} while (std::next_permutation(combination, combination + 3)); // produces all combinationsdelete 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 ...
Access this course and 1400+ top-rated courses and projects.