1. Brute Force — Generate All Pairings
Intuition
Recursively generate all valid ways to pair the 2n elements, compute the sum of minimums for each pairing, and return the maximum.
Algorithm
- Track used elements with a boolean visited array.
- Find the first unvisited element at index i.
- Pair it with every subsequent unvisited element at index j (j > i).
- Mark i and j as visited, recursively solve for remaining elements, and add min(nums[i], nums[j]).
- Backtrack by unmarking i and j to explore other pairings.
- Return the maximum sum found across all complete pairings.
Brute Force All Partition Pairings
2 of 2 questions left todayStep 1: Test grouping (1, 4) and (3, 2)
Step 1: Test grouping (1, 4) and (3, 2). Minimum sum is 1 + 2 = 3. Set maxSum = 3.
#include <algorithm>#include <climits>#include <iostream>#include <vector>using namespace std; // Brute force helper to explore all pairingsint findMaxPairSum(vector<int>& nums, vector<bool>& visited, int count) { int n = nums.size(); if (count == n) return 0; // All elements paired // Find first unvisited element int first = -1; for (int i = 0; i < n; i++) { if (!visited[i]) { first = i; break; } } if (first == -1) return 0; visited[first] = true; int maxSum = INT_MIN; // Try pairing __SF_TOKEN_A__ with every other unvisited element for (int j = first + 1; j < n; j++) { if (!visited[j]) { visited[j] = true; int currentSum = min(nums[first], nums[j]) + findMaxPairSum(nums, visited, count + 2); maxSum = max(maxSum, currentSum); visited[j] = false; // Backtrack } } visited[first] = false; // Backtrack return maxSum;} int arrayPairSumBruteForce(vector<int>& nums) { vector<bool> visited(nums.size(), false); return findMaxPairSum(nums, visited, 0);} int main() { vector<int> nums = {1, 4, 3, 2}; cout << "Output: " << arrayPairSumBruteForce(nums) << endl; return 0;}Time & Space Complexity
- Time complexity:
O((2N)!)— The number of ways to partition 2N elements into N pairs is (2N - 1) × (2N - 3) × ... × 1 = (2N)! / (2N × N!), which grows factorially. - Space complexity:
O(N)— The recursive call stack reaches a maximum depth of N (where 2N is array length), using O(N) auxiliary stack space.
Why Brute Force Doesn't Scale:
For N = 10 (array size 20), there are over 654 million possible pairings to check. For N = 10,000, the number of permutations exceeds the number of atoms in the universe.
By mathematical proof, pairing adjacent elements in sorted order always minimizes the sacrifice of large numbers, reducing the problem from factorial time down to standard O(N log N) sorting.
At 2N = 20: Brute force checks 654,729,075 pairings (~2.5s). Sorting takes 20 log(20) ≈ 86 ops (< 0.001ms).