You are given an integer array nums
of 2n
integers. Your task is to:
n
pairs such that:
(a_i, b_i)
, the result of min(a_i, b_i)
is maximized.nums = [1,4,3,2]
4
(1, 2)
and (3, 4)
. The sum of minimums is 1 + 3 = 4
.Q: Can the array nums
contain both positive and negative integers?
A: Yes, the array can contain both positive and negative integers.
Q: Is the number of elements in the list nums
always even?
A: Yes, the given problem guarantees that nums
will have 2n
elements, thus it will always have an even number of elements.
Q: Can there be duplicate elements in the array nums
?
A: Yes, duplicate elements are allowed.
The strategy revolves around sorting the array first and then pairing the elements such that we maximize the sum of the smallest elements in each pair. By sorting the array, we can simply pair adjacent elements to achieve this:
(a, b)
will be (nums[i], nums[i+1])
where nums[i]
is always the smaller or equal member.def arrayPairSum(nums: list) -> int:
# Sort the array first
nums.sort()
# Initialize the sum
result = 0
# Sum the minimum of each pair
for i in range(0, len(nums), 2):
result += nums[i]
return result
# Example Usage
nums = [1, 4, 3, 2]
print(arrayPairSum(nums)) # Output: 4
nums = [1, 2, 3, 4]
, the pairs will be (1, 2)
and (3, 4)
.1
and 3
.1 + 3 = 4
.nums
.Thus, the overall time complexity is dominated by the sorting step and is (O(n \log n)).
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?