1. Brute Force — Sort Array on Every Smash
Intuition
Keep array sorted ascending. While length > 1, remove the last two elements. If they differ, append the difference and re-sort. Return last element or 0.
When to apply: When stones array is tiny (N <= 30) and no heap is available.
Algorithm
- Step 1: While array size > 1:
- Step 2: Sort array ascending.
- Step 3: Pop last two elements y and x.
- Step 4: If y != x, append y - x.
- Step 5: Return array[0] if size == 1, else 0.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: int lastStoneWeight(vector<int>& stones) { while (stones.size() > 1) { sort(stones.begin(), stones.end()); int y = stones.back(); stones.pop_back(); int x = stones.back(); stones.pop_back(); if (y != x) { stones.push_back(y - x); } } return stones.empty() ? 0 : stones[0]; }}; int main() { Solution sol; vector<int> stones = {2, 7, 4, 1, 8, 1}; cout << "Last Stone Weight (Brute Force): " << sol.lastStoneWeight(stones) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2 log N)— O(N2 log N) repeated sorting. - Space complexity:
O(N)— O(N) storage.
Why Brute Force Doesn't Scale:
With N = 105, repeated sorting takes ~1010 operations. Max-Heap takes ~1.7 * 106 operations.
Max-Heap takes ~1ms for standard arrays.