Given an integer array nums of 2n integers, 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.
Example 1:
Input: nums = [1,4,3,2] Output: 4 Explanation: All possible pairings (ignoring the ordering of elements) are: 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 So the maximum possible sum is 4.
Example 2:
Input: nums = [6,2,6,5,1,2] Output: 9 Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
Constraints:
1 <= n <= 104nums.length == 2 * n-104 <= nums[i] <= 104The core idea of this approach is to pair up the elements after sorting the array to maximize the minimum sum of pairs. By sorting the array, the smallest values are naturally grouped together, maximizing your result. After sorting, pair the elements from the start with their consecutive neighbor. This guarantees maximal sum of mins in pairs.
Let us see how we can implement this in various programming languages:
The C code starts by sorting the array using the built-in qsort() function. Once sorted, we iterate over the array taking sum of every alternate element starting from index 0, because these represent the minimum in every pair if paired in sorted order.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) as no additional space is used except for input.
Instead of using a traditional sorting method, we can optimize the sorting step with a counting sort. This is particularly useful given the constraints - limited range of numbers. This approach uses a counting array to sort, followed by picking elements at alternate indices in a manner similar to the previous approach.
This C implementation utilizes counting sort for the defined range of input values. We update a count array and adjust it for each occurrence shifting values. The iteration through the count array allows us to easily compute the required sum by alternating over counts.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n + range) due to counting sort.
Space Complexity: O(range) for the count array.
| Approach | Complexity |
|---|---|
| Sorting and Pairing Strategy | Time Complexity: O(n log n) due to sorting. |
| Greedy Pairing Strategy with Counting Sort Optimization | Time Complexity: O(n + range) due to counting sort. |
Maximum Subarray - Kadane's Algorithm -- Leetcode 53 • Greg Hogg • 366,971 views views
Watch 9 more video solutions →Practice Array Partition with our built-in code editor and test cases.
Practice on FleetCode