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.
1function minPairSum(nums) {
2 nums.sort((a, b) => a - b);
3 let maxSum = 0;
4 for (let i = 0; i < nums.length / 2; i++) {
5 const pairSum = nums[i] + nums[nums.length - 1 - i];
6 if (pairSum > maxSum) {
7 maxSum = pairSum;
8 }
9 }
10 return maxSum;
11}
12
13// Test
14evenArray = [3, 5, 2, 3];
15console.log('Output:', minPairSum(evenArray)); // Output: 7
The JavaScript solution employs the array sort()
method for sorting, coupled with a for-loop to accomplish the pairing and identification of the highest sum.
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#include <vector>
#include <algorithm>
int minPairSum(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
int maxSum = 0, pairSum;
for (size_t i = 0; i < nums.size() / 2; ++i) {
pairSum = nums[i] + nums[nums.size() - 1 - i];
maxSum = std::max(maxSum, pairSum);
}
return maxSum;
}
int main() {
std::vector<int> nums = {3, 5, 2, 3};
int result = minPairSum(nums);
std::cout << "Output: " << result << std::endl;
return 0;
}
The solution divides and conquers by directly selecting indices from ends towards the center of the sorted vector, essentially making direct index-based pairings.