Sponsored
Sponsored
Sort the array first. Then, use a two-pointer technique to pick the smallest and largest elements to form pairs. Start with the smallest, pair it with the largest, and move inwards. This minimizes the largest sum in each pair.
The time complexity is O(n log n) due to the sorting step, and the space complexity is O(1) as we don't use any additional data structures.
1using System;
2
3public class Solution {
4 public int MinPairSum(int[] nums) {
5 Array.Sort(nums);
6 int maxSum = 0;
7 for (int i = 0; i < nums.Length / 2; i++) {
8 int pairSum = nums[i] + nums[nums.Length - 1 - i];
9 if (pairSum > maxSum) {
10 maxSum = pairSum;
11 }
12 }
13 return maxSum;
14 }
15
16 public static void Main() {
17 Solution sol = new Solution();
18 int[] nums = {3, 5, 2, 3};
19 Console.WriteLine("Output: " + sol.MinPairSum(nums)); // Output should be 7
20 }
21}
The C# implementation uses Array.Sort
to sort the array and a for-loop to determine the maximum sum by forming pairs from sorted ends towards the center.
Use the sorted array but pair elements directly based on their index positions in a staggered manner. This approach takes advantage of the sorted order to pair elements directly based on their index positions.
The time complexity remains O(n log n) due to sorting, and the space complexity is O(1).
1
public class Solution {
public int MinPairSum(int[] nums) {
Array.Sort(nums);
int maxSum = 0, pairSum;
for (int i = 0; i < nums.Length / 2; ++i) {
pairSum = nums[i] + nums[nums.Length - 1 - i];
if (pairSum > maxSum)
maxSum = pairSum;
}
return maxSum;
}
public static void Main() {
Solution sol = new Solution();
int[] nums = {3, 5, 2, 3};
Console.WriteLine("Output: " + sol.MinPairSum(nums));
}
}
The C# version forms pairs from opposite ends of the sorted array, ensuring the minimum possible maximum pair sum.