Given an integer array nums of 2n integers, your task is to group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
Input: nums = [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is min(1, 2) + min(3, 4) = 1 + 3 = 4.
Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: n is 3, and the maximum sum of pairs is min(1, 2) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
Q: What is the range of values in the array? A: The values can be any integer within the range defined by the problem constraints.
Q: Can nums contain duplicate elements?
A: Yes, nums can have duplicate elements.
Q: Is the input array always guaranteed to be of even length?
A: Yes, as per the problem description, the array length will be 2n.
nums.min(ai, bi) as the minimum of each pair would always be the first element of the sorted pair, and it will accumulate the smallest values first.public class Solution {
public int arrayPairSum(int[] nums) {
// Sort the array
Arrays.sort(nums);
int sum = 0;
// Iterate through the array, taking every second element starting from index 0
for (int i = 0; i < nums.length; i += 2) {
sum += nums[i];
}
return sum;
}
}
O(n log n) where n is the number of elements in the array nums.O(1) if we do not account for the space taken by the sorting algorithm itself (assuming it’s an in-place sort). Sorting typically requires O(n) space for auxiliary arrays if the sorting algorithm is not in-place.This approach ensures that we achieve the maximum sum of min(ai, bi) for given pairs.
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?