1. Brute Force — Compute All N^2 Sums & Sort
Intuition
Run two nested loops over A and B. Store all sums in an array. Sort descending and return first K elements.
When to apply: When N is small (N <= 500).
Algorithm
- Step 1: Compute all A[i] + B[j] sums.
- Step 2: Sort all sums descending.
- Step 3: Slice and return first K sums.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: vector<int> maxCombinations(vector<int>& A, vector<int>& B, int K) { vector<int> allSums; for (int a : A) { for (int b : B) { allSums.push_back(a + b); } } sort(allSums.begin(), allSums.end(), greater<int>()); return vector<int>(allSums.begin(), allSums.begin() + K); }}; int main() { Solution sol; vector<int> A = {3, 2}, B = {1, 4}; auto res = sol.maxCombinations(A, B, 2); cout << "K Max Combinations (Brute Force): "; for (int x : res) cout << x << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2 log(N^2))— O(N2 log N) from sorting all pairs. - Space complexity:
O(N^2)— O(N2) memory to hold sums.
Why Brute Force Doesn't Scale:
With N = 105, N2 = 1010 pairs, crashing memory and taking minutes. The optimal heap visits only 2K states (~20,000 for K = 10,000).
Runs in ~15ms for N = 100,000, K = 10,000.