

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Questions & Answers
- Maximum Possible Sum of Products in JavaScript
- Find Sum of pair from two arrays with maximum sum in C++
- Find required sum pair with JavaScript
- Find maximum sum possible equal sum of three stacks in C++
- XOR of Sum of every possible pair of an array in C++
- Pair whose sum exists in the array in JavaScript
- Find the Pair with a Maximum Sum in a Matrix using C++
- Subset with maximum sum in JavaScript
- C++ program to find maximum possible value for which XORed sum is maximum
- C++ program to find maximum possible value of XORed sum
- Find Maximum difference pair in Python
- Maximum contiguous sum of subarray in JavaScript
- C++ Program to find maximum possible smallest time gap between two pair of clock readings
- Sum of All Possible Odd Length Subarrays in JavaScript
- Maximum Length of Pair Chain in C++
Advertisements