Given a 0-indexed integer array nums
, the sum of two elements nums[i]
and nums[j]
(where i != j
) is called a pair sum. Suppose the maximum pair sum in an array is the largest such sum.
Return the maximum pair sum that can be formed in the array.
Example 1:
Input: nums = [5,6,2,7,4]
Output: 13
Explanation: The pair (6, 7) forms the maximum pair sum 13.
Example 2:
Input: nums = [1,2,3,4]
Output: 7
Explanation: The pair (3, 4) forms the maximum pair sum 7.
nums
?
To solve this problem, we need to identify the two largest numbers in the array, as their sum would be the maximum pair sum.
Steps:
Time Complexity Analysis:
def max_pair_sum(nums):
# Sort the array
nums.sort()
# The maximum pair sum is the sum of the last two elements
return nums[-1] + nums[-2]
# Test Cases
print(max_pair_sum([5, 6, 2, 7, 4])) # Output: 13
print(max_pair_sum([1, 2, 3, 4])) # Output: 7
This code will effectively provide the maximum pair sum by first sorting the array and then summing the two largest elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?