
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.
1def arrayPairSum(nums):
2 nums.sort()
3 return sum(nums[i] for i in range(0, len(nums), 2))
4
5nums = [6, 2, 6, 5, 1, 2]
6result = arrayPairSum(nums)
7print(result)In Python, the function sorts the list using sort(). Then, it sums every second element starting from 0 using list comprehension.
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
class Program
{
static int ArrayPairSum(int[] nums)
{
int[] count = new int[20001];
foreach (var num in nums)
{
count[num + 10000]++;
}
int sum = 0;
bool odd = true;
for (int i = 0; i < count.Length; i++)
{
while (count[i] > 0)
{
if (odd)
{
sum += i - 10000;
}
odd = !odd;
count[i]--;
}
}
return sum;
}
static void Main()
{
int[] nums = {6, 2, 6, 5, 1, 2};
int result = ArrayPairSum(nums);
Console.WriteLine(result);
}
}C# executes a counting strategy using a pre-sized array, offset adjustments lead to nutrition of elements into pairs in an optimized solution.