561. Array Partition
Description
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.
Examples
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.
info
You can read the full description here.
Solution 1
Approach
- To keep large numbers from the min function, you should make pairs with similar values. So sort is necessary.
.sort()
is faster thansorted()
Implementation
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[::2])
Complexity Analysis
- : number of integers
- Time Complexity:
- sort:
- slicing:
- Space Complexity:
Solutions from the Book
info
The original source of codes below is here.
Solution 2
Approach: Sort in ascending order
- Append numbers in an array and sort them.
- Traverse the array and put the numbers in a temporary array.
- When the length of the temporary array is 2, add the minimum value to total sum.
Implementation
from typing import List
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
sum = 0
pair = []
nums.sort()
for n in nums:
pair.append(n)
if len(pair) == 2:
sum += min(pair)
pair = []
return sum
Solution 3
Approach: Calculate with nth numbers (n : even)
- Almost same with
Solution 1
. - Traverse the array with
enumerate
, and check whether index is even or not.
Implementation
from typing import List
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
sum = 0
nums.sort()
for i, n in enumerate(nums):
if i % 2 == 0:
sum += n
return sum
Solution 4
Approach: Phythonic solution with slicing
- With slicing, the implementation code becomes very simple.
- Also, it's the fastest way!
Implementation
from typing import List
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
return sum(sorted(nums)[::2])