
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Maximum Possible Sum of Products in JavaScript
- Find maximum sum possible equal sum of three stacks in C++
- Find Sum of pair from two arrays with maximum sum in C++
- Subset with maximum sum in JavaScript
- XOR of Sum of every possible pair of an array in C++
- Find required sum pair with JavaScript
- C++ program to find maximum possible value for which XORed sum is maximum
- Pair whose sum exists in the array in JavaScript
- Maximum contiguous sum of subarray in JavaScript
- Find the Pair with a Maximum Sum in a Matrix using C++
- C++ program to find maximum possible value of XORed sum
- Sum of All Possible Odd Length Subarrays in JavaScript
- Maximum subarray sum in circular array using JavaScript
- C++ Program to find maximum possible smallest time gap between two pair of clock readings
- JavaScript Program for Maximum equilibrium sum in an array

Advertisements