easy Array Partition
Problem Statement
Given an array of integers nums containing 2n integers, group these integers into n pairs (a
Return the maximum possible sum of these minimum values.
Examples
-
Example 1:
- Input: nums =
[5, 3, 1, 2, 4, 6, 1, 4] - Output:
12 - Explanation: Pair the integers as (1, 1), (2, 3), (4, 4) and (5, 6). The sum of the minimums is 1 + 2 + 4 + 5 = 12.
- Input: nums =
-
Example 2:
- Input: nums =
[1, 1, 1, 1, 2, 2] - Output:
4 - Explanation: Pair the integers as (1, 1), (1, 1), and (2, 2). The sum of the minimums is 1 + 1 + 2 = 4.
- Input: nums =
-
Example 3:
- Input: nums =
[8, 9, 5, 6, 3, 4] - Output:
16 - Explanation: Pair the integers as (3, 4), (5, 6), and (8, 9). The sum of the minimums is 3 + 5 + 8 = 16.
- Input: nums =
Constraints:
- 1 <= n <= 104
- nums.length == 2 * n
- -104 <= nums[i] <= 104
Try it yourself
Try solving this question here:
✅ Solution Array Partition
Problem Statement
Given an array of integers nums containing 2n integers, group these integers into n pairs (a
Return the maximum possible sum of these minimum values.
Examples
-
Example 1:
- Input: nums =
[5, 3, 1, 2, 4, 6, 1, 4] - Output:
12 - Explanation: Pair the integers as (1, 1), (2, 3), (4, 4) and (5, 6). The sum of the minimums is 1 + 2 + 4 + 5 = 12.
- Input: nums =
-
Example 2:
- Input: nums =
[1, 1, 1, 1, 2, 2] - Output:
4 - Explanation: Pair the integers as (1, 1), (1, 1), and (2, 2). The sum of the minimums is 1 + 1 + 2 = 4.
- Input: nums =
-
Example 3:
- Input: nums =
[8, 9, 5, 6, 3, 4] - Output:
16 - Explanation: Pair the integers as (3, 4), (5, 6), and (8, 9). The sum of the minimums is 3 + 5 + 8 = 16.
- Input: nums =
Constraints:
- 1 <= n <= 104
- nums.length == 2 * n
- -104 <= nums[i] <= 104
Solution
To solve this problem, we use a counting sort approach to sort the array efficiently. The idea is to pair elements in a way that maximizes the sum of the minimum values of the pairs. By sorting the array and then pairing every two consecutive elements, we ensure that we always include the smallest possible element of each pair in the sum. This strategy works because, in a sorted array, every alternate element, starting from the smallest, will contribute to the maximum sum of the minimums.
Step-by-Step Algorithm
-
Initialize Variables:
- Create an array
countof size 20001 to hold the frequency of each element. The size is2 * max + 1because we need to account for both positive and negative numbers within the range [-10000, 10000]. - Initialize
sumto 0, which will hold the final result. - Initialize a boolean
addtotrue, which will help in toggling between adding elements to the sum or not. It ensures that we select every alternate element in the sorted array.
- Create an array
-
Calculate the Frequency of Elements:
- Loop through each element
numinnums. - For each
num, increment the count at indexnum + max. This step maps negative numbers to positive indices in thecountarray.
- Loop through each element
-
Traverse the Count Array:
- Iterate through the
countarray from index 0 to 20000. - For each index
i, whilecount[i]is greater than 0:- If
addistrue, addi - maxtosum. This step takes the value mapped by the count array back to its original range. This step effectively helps in handling negative elements. - Toggle
addto its opposite value. This ensures that we add every second element. - Decrement
count[i]by 1, indicating that we have processed one occurrence of the number.
- If
- Iterate through the
-
Return Result:
- Return the final value of
sumas the result.
- Return the final value of
Algorithm Walkthrough
Given nums = [5, 3, 1, 2, 4, 6, 1, 4]:
-
Initialize Variables:
max = 10000countarray of size 20001 initialized to all zeros.sum = 0add = true
-
Fill the Count Array:
- For
num = 5:count[5 + 10000]++→count[10005] = 1 - For
num = 3:count[3 + 10000]++→count[10003] = 1 - For
num = 1:count[1 + 10000]++→count[10001] = 1 - For
num = 2:count[2 + 10000]++→count[10002] = 1 - For
num = 4:count[4 + 10000]++→count[10004] = 1 - For
num = 6:count[6 + 10000]++→count[10006] = 1 - For
num = 1:count[1 + 10000]++→count[10001] = 2 - For
num = 4:count[4 + 10000]++→count[10004] = 2
- For
-
Traverse the Count Array:
- Starting from index 0 to 20000:
- Indices with counts:
count[i] = count[10001] = 2- First occurrence:
add = true, add1tosum→sum = sum + i - max = 0 + 10001 - 10000 = 1, toggleaddtofalse, decrementcount[10001] - Second occurrence:
add = false, do not add, toggleaddtotrue, decrementcount[10001]
- First occurrence:
count[i] = count[10002] = 1- First occurrence:
add = true, add2tosum→sum = 3, toggleaddtofalse, decrementcount[10002]
- First occurrence:
count[i] = count[10003] = 1- First occurrence:
add = false, do not add, toggleaddtotrue, decrementcount[10003]
- First occurrence:
count[i] = count[10004] = 2- First occurrence:
add = true, add4tosum→sum = 7, toggleaddtofalse, decrementcount[10004] - Second occurrence:
add = false, do not add, toggleaddtotrue, decrementcount[10004]
- First occurrence:
count[i] = count[10005] = 1- First occurrence:
add = true, add5tosum→sum = 12, toggleaddtofalse, decrementcount[10005]
- First occurrence:
count[i] = count[10006] = 1- First occurrence:
add = false, do not add, toggleaddtotrue, decrementcount[10006]
- First occurrence:
- Indices with counts:
- Starting from index 0 to 20000:
-
Return Result:
- The final value of
sumis12.
- The final value of
Code
class Solution {
// Method to find the maximum sum of min pairs
public int arrayPairSum(int[] nums) {
// Determine the maximum value in the array to define the range for counting sort
int max = 10000; // given constraint for the problem
// Array to store the frequency of each element
int[] count = new int[2 * max + 1];
// Fill the count array
for (int num : nums) {
count[num + max]++;
}
// Initialize variables for calculating the sum and a flag to toggle between pairs
int sum = 0;
boolean add = true;
// Traverse the count array
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
// Add to sum if the flag is true
if (add) {
sum += i - max;
}
// Toggle the flag
add = !add;
// Decrement the count for the current number
count[i]--;
}
}
return sum;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test case 1
int[] nums1 = { 5, 3, 1, 2, 4, 6, 1, 4 };
int result1 = solution.arrayPairSum(nums1);
System.out.println("Test Case 1 Result: " + result1); // Expected Output: 12
// Test case 2
int[] nums2 = { 1, 1, 1, 1, 2, 2 };
int result2 = solution.arrayPairSum(nums2);
System.out.println("Test Case 2 Result: " + result2); // Expected Output: 4
// Test case 3
int[] nums3 = { 8, 9, 5, 6, 3, 4 };
int result3 = solution.arrayPairSum(nums3);
System.out.println("Test Case 3 Result: " + result3); // Expected Output: 16
}
}
Complexity Analysis
Time Complexity
-
Calculating elements frequency:
- This step involves iterating over the input array
numsand updating the count array. The time complexity for this step is, where nis the length of thenumsarray.
- This step involves iterating over the input array
-
Traversing the Count Array:
- The count array is traversed, and each element is processed to calculate the sum of the minimum values of the pairs. Since the count array has a fixed size
(20001), this step takestime.
- The count array is traversed, and each element is processed to calculate the sum of the minimum values of the pairs. Since the count array has a fixed size
Therefore, the overall time complexity of the algorithm is: n is the number of elements in the input array nums.
Space Complexity
- Count Array:
- The count array requires a fixed amount of space, regardless of the input size. The space required is O(20001), which simplifies to
due to the fixed upper bound on the size of the array elements.
- The count array requires a fixed amount of space, regardless of the input size. The space required is O(20001), which simplifies to
🤖 Don't fully get this? Learn it with Claude
Stuck on Array Partition? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Array Partition** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Array Partition** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Array Partition**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Array Partition**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.