1. Brute Force — Greedy by Maximum Value Alone (Flawed Baseline)
Intuition
Sort items descending by total value alone. Greedily pack items by value. Demonstrates the pitfall of prioritizing raw value over efficiency.
When to apply: Baseline comparison showing why value density is required.
Algorithm
- Step 1: Sort items in descending order of value.
- Step 2: While remaining capacity > 0 and items remain: take whole or fractional item.
- Step 3: Return accumulated value.
#include <iostream>#include <vector>#include <algorithm> using namespace std; struct Item { int value, weight;}; class Solution {public: double fractionalKnapsack(int w, vector<Item>& items) { sort(items.begin(), items.end(), [](const Item& a, const Item& b) { return a.value > b.value; }); double totalVal = 0.0; int curWeight = 0; for (const auto& item : items) { if (curWeight + item.weight <= w) { curWeight += item.weight; totalVal += item.value; } else { int remain = w - curWeight; totalVal += (double)item.value * ((double)remain / item.weight); break; } } return totalVal; }}; int main() { Solution sol; vector<Item> items = {{60, 10}, {100, 20}, {120, 30}}; cout << "Max value: " << sol.fractionalKnapsack(50, items) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Sorting takes O(N log N). Single pass takes O(N). - Space complexity:
O(1) auxiliary— No extra storage beyond variables.
Why Brute Force Doesn't Scale:
With N = 105, an O(N2) or recursion approach times out. O(N log N) ratio sorting runs in ~25ms.
For N = 100,000 items: O(N log N) requires ~1.7 * 106 comparisons, completing well within time limit.