Similar Problems

Similar Problems not available

Divide Array Into Equal Pairs - Leetcode Solution

Companies:

LeetCode:  Divide Array Into Equal Pairs Leetcode Solution

Difficulty: Easy

Topics: hash-table bit-manipulation array  

The problem statement for "Divide Array Into Equal Pairs" on LeetCode is:

Given an integer array nums of even length, pair up the elements of nums into n/2 pairs such that:

  • Each element of nums is in exactly one pair, and
  • The maximum sum of any pair is minimized.

Return the minimized maximum sum.

In other words, we need to find the minimum possible value of the maximum sum of any pair of numbers that can be formed from the given array. Each element can be in only one pair, and we need to pair them up in such a way that the maximum sum of any pair is minimized.

Solution:

We can start by sorting the array in ascending order. Once the array is sorted, we can pair up the elements starting from the first and the last element, second and second-last, and so on. This way, we can ensure that the maximum element from each pair will be as small as possible, which will result in a minimized maximum sum.

Here's the code in Python:

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        # sort the array
        nums.sort()
        # initialize sum
        total_sum = 0
        # pair up elements and compute sum
        for i in range(0, len(nums), 2):
            total_sum += min(nums[i], nums[i+1])
        # return sum
        return total_sum

In this code, we first sort the input array using the sort() function. We then initialize a variable total_sum to 0. We then pair up the elements starting from the first and the last element, second and second-last, and so on. For each pair, we take the minimum of the two elements using the min() function and add it to the total_sum variable.

Finally, we return the value of total_sum, which will be the minimized maximum sum of any pair of numbers that can be formed from the given array.

This algorithm has a time complexity of O(n log n) due to the sorting of the input array, where n is the length of the input array. However, since the input is an even-length array, we can simplify the time complexity to O(n) assuming that the sorting takes O(n log n) time.

Divide Array Into Equal Pairs Solution Code

1