




Sponsored
The core idea of this approach is to pair up the elements after sorting the array to maximize the minimum sum of pairs. By sorting the array, the smallest values are naturally grouped together, maximizing your result. After sorting, pair the elements from the start with their consecutive neighbor. This guarantees maximal sum of mins in pairs.
Let us see how we can implement this in various programming languages:
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) as no additional space is used except for input.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int arrayPairSum(std::vector<int>& nums) {
6    std::sort(nums.begin(), nums.end());
7    int sum = 0;
8    for (int i = 0; i < nums.size(); i += 2) {
9        sum += nums[i];
10    }
11    return sum;
12}
13
14int main() {
15    std::vector<int> nums = {6, 2, 6, 5, 1, 2};
16    int result = arrayPairSum(nums);
17    std::cout << result << std::endl;
18    return 0;
19}In this C++ implementation, we sort the vector using std::sort(). By iterating through the array and summing up the values at even indices, we get the desired result.
Instead of using a traditional sorting method, we can optimize the sorting step with a counting sort. This is particularly useful given the constraints - limited range of numbers. This approach uses a counting array to sort, followed by picking elements at alternate indices in a manner similar to the previous approach.
Time Complexity: O(n + range) due to counting sort.
Space Complexity: O(range) for the count array.
1
This C implementation utilizes counting sort for the defined range of input values. We update a count array and adjust it for each occurrence shifting values. The iteration through the count array allows us to easily compute the required sum by alternating over counts.