Array Partition

Problem 🤔

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).


def quickSort(self,nums, low, high):
    if low < high:
        part = self.partition(nums, low,high)

def partition(self, nums, low, high):
    i = (low - 1)
    pivot = nums[high]
    for j in range(low, high):
        if nums[j] <= pivot:
            i += 1
            nums[i],nums[j] = nums[j],nums[i]
    nums[i+1],nums[high] = nums[high],nums[i+1]

def arrayPairSum(self, nums):
    temp = 0
    for index in range(0,len(nums)-1,2):
        temp += min(nums[index],nums[index+1])
    return temp

Developer’s Notes 👨‍💻

For this I ordered the list using a quicksort, then I cycled through the array took the pairs of numbers and summed the mins. I ordered the array since it would give the largest possible minimum for each pair.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s