




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 <stdio.h>
2#include <stdlib.h>
3
4int compare(const void *a, const void *b) {
5    return (*(int*)a - *(int*)b);
6}
7
8int arrayPairSum(int* nums, int numsSize) {
9    qsort(nums, numsSize, sizeof(int), compare);
10    int sum = 0;
11    for (int i = 0; i < numsSize; i += 2) {
12        sum += nums[i];
13    }
14    return sum;
15}
16
17int main() {
18    int nums[] = {6, 2, 6, 5, 1, 2};
19    int result = arrayPairSum(nums, 6);
20    printf("%d", result);
21    return 0;
22}The C code starts by sorting the array using the built-in qsort() function. Once sorted, we iterate over the array taking sum of every alternate element starting from index 0, because these represent the minimum in every pair if paired in sorted order.
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    
Using prepared range for integer storing, Java implementation optimizes the typical sort and sum operation to perform efficiently on arbitrary arrays fitting the constraints.