Pair of (adjacent) elements of an array whose sum is lowest JavaScript


We are required to write a JavaScript function that takes in an array of numbers. The function should return a subarray of two adjacent elements from the original array whose sum is the least amongst all adjacent pairs of the array.

If the length of the array is less than 2, we should return boolean false.

For example, If the input array is −

const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2];

Here, the sum of pair [-23, 1] is -22 which is the least for any two adjacent elements of the array, so the function should return [-23, 1]

The code for this will be −

const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2];
const leastSum = arr => {
   if(arr.length <= 2){
      return false;
   };
   const creds = arr.reduce((acc, val, ind) => {
      let { smallest, startIndex } = acc;
      const next = arr[ind+1] ;
      if(!next){
         return acc;
      }
      const sum = val + next;
      if(sum < smallest){
         startIndex = ind;
         smallest = sum;
      };
      return { startIndex, smallest };
   }, {
      smallest: Infinity,
      startIndex: -1
   });
   const { startIndex } = creds;
   return [arr[startIndex], arr[startIndex + 1]];
};
console.log(leastSum(arr));

Following is the output on console −

[-23, 1]

Updated on: 09-Oct-2020

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements