Achieving maximum possible pair sum in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of integers, arr, which is of length 2n as the first and the only argument.

The task of our function 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.

For example, if the input to the function is −

const arr = [1, 4, 3, 2];

Then the output should be −

const output = 4;

Output Explanation

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

Example

Following is the code −

 Live Demo

const arr = [1, 4, 3, 2];
const pairSum = (arr = []) => {
   arr.sort((a, b) => a - b)
   let sum = 0
   for (let i = 0; i < arr.length; i += 2) {
      sum += Math.min(arr[i], arr[i + 1])
   }
   return sum
}
console.log(pairSum(arr));

Output

Following is the console output −

4

Updated on: 21-Apr-2021

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements