1. Brute Force — Linear Scan Merge
Intuition
Loop N-1 times. Find the minimum element, remove it, find the second minimum, remove it, add their sum to total cost, and append the sum.
When to apply: When external libraries are unavailable and N is small (N <= 100).
Algorithm
- Step 1: Check if size <= 1; return 0.
- Step 2: Repeat N-1 times: find min1, remove; find min2, remove.
- Step 3: cost += min1 + min2.
- Step 4: Append min1 + min2.
- Step 5: Return total cost.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: long long minCost(vector<long long>& arr) { if (arr.size() <= 1) return 0; long long total = 0; while (arr.size() > 1) { auto it1 = min_element(arr.begin(), arr.end()); long long a = *it1; arr.erase(it1); auto it2 = min_element(arr.begin(), arr.end()); long long b = *it2; arr.erase(it2); long long sum = a + b; total += sum; arr.push_back(sum); } return total; }}; int main() { Solution sol; vector<long long> arr = {4, 3, 2, 6}; cout << "Min Cost (Brute Force): " << sol.minCost(arr) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— O(N2) due to repeated linear scans. - Space complexity:
O(N)— O(N) to store dynamic rope list.
Why Brute Force Doesn't Scale:
For N = 105, O(N2) takes ~1010 operations, whereas Min-Heap takes ~1.7 * 106 operations.
Min-Heap completes in ~20ms for N = 100,000 ropes.