1. Brute Force — Repeated Minimum Search in Array
Intuition
At each step of merging, find the index of the minimum element, remove it, then find the index of the second minimum element, add their sum to total cost, and insert the sum back into the array. Repeat until the array size is 1.
When to apply: When external libraries and heap data structures cannot be used and N is small (N <= 100).
Algorithm
- Step 1: Check if array has 1 or 0 elements; if so, return 0.
- Step 2: While array size > 1, scan array to find index of smallest stick min1.
- Step 3: Scan array to find index of second smallest stick min2.
- Step 4: Sum = min1 + min2. Add sum to total cost.
- Step 5: Remove min1 and min2 from array, append sum.
- Step 6: Repeat until 1 stick remains. Return total cost.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: int connectSticks(vector<int>& sticks) { if (sticks.size() <= 1) return 0; int totalCost = 0; while (sticks.size() > 1) { auto it1 = min_element(sticks.begin(), sticks.end()); int min1 = *it1; sticks.erase(it1); auto it2 = min_element(sticks.begin(), sticks.end()); int min2 = *it2; sticks.erase(it2); int combined = min1 + min2; totalCost += combined; sticks.push_back(combined); } return totalCost; }}; int main() { Solution sol; vector<int> sticks = {2, 4, 3}; cout << "Minimum Cost (Brute Force): " << sol.connectSticks(sticks) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— O(N2) because each iteration finds the minimum in linear time. - Space complexity:
O(N)— O(N) to store copies of elements.
Why Brute Force Doesn't Scale:
With N = 105, an O(N2) brute force takes ~1010 operations which times out. Min-Heap scales to O(N log N) (~1.7 * 106 operations).
For N = 100,000, Min-Heap takes ~15ms whereas O(N2) takes several minutes.