Skip to content

561. Array Partition 👍

  • Time: $O(n) \to O(n\log n)$$
  • Space: $O(n) \to O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int arrayPairSum(vector<int>& nums) {
    int ans = 0;

    sort(begin(nums), end(nums));

    for (int i = 0; i < nums.size(); i += 2)
      ans += nums[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int arrayPairSum(int[] nums) {
    int ans = 0;

    Arrays.sort(nums);

    for (int i = 0; i < nums.length; i += 2)
      ans += nums[i];

    return ans;
  }
}
1
2
3
class Solution:
  def arrayPairSum(self, nums: List[int]) -> int:
    return sum(sorted(nums)[::2])