Algorithm to identify the highest sum of two numbers in a disorganized array of whole numbers

I am looking to create a function that can identify the largest pair sum in an unordered sequence of numbers.

largestPairSum([10, 14, 2, 23, 19]) --> 42 (sum of 23 and 19)
largestPairSum([99, 2, 2, 23, 19])  --> 122 (sum of 99 and 23)
largestPairSum([-10,-20,-30,-40])   --> -30 (sum of -10 and -20)

My Attempt:

function largestPairSum(numbers)
{
   let counter = 0;
   let orderedNumbers = numbers.sort();

   if (orderedNumbers[0] === -orderedNumbers[0]) {
       orderedNumbers.reverse();
       counter = orderedNumbers[0] + orderedNumbers[1];
       }

   else {
       counter = orderedNumbers[-1] + orderedNumbers[-2];
    }
  return counter;
}

Upon running the function, it returns 'NaN'. I tried checking the type using:


console.log(typeof(orderedNumbers[0]));

The type was shown as 'number', so I'm uncertain about where the issue lies. Thank you for your assistance!

Answer №1

Unfortunately, your approach is not effective due to:

  • sorting by string ascending (standard without callback)
  • using negative indices.

Instead, consider sorting in descending order and selecting the first two elements.

function largestPairSum(numbers) {
    numbers.sort((a, b) => b - a);

    return numbers[0] + numbers[1];
}

console.log(largestPairSum([10, 14, 2, 23, 19])); // 42 (23 + 19)
console.log(largestPairSum([99, 2, 2, 23, 19]));  // 122 (99 + 23)
console.log(largestPairSum([-10, -20, -30, -40])) // -30 (-10 + -20)

An alternative solution that does not require sorting.

function largestPairSum(numbers) {
    let largest = numbers.slice(0, 2),
        smallest = largest[0] < largest[1] ? 0 : 1;

    for (let i = 2; i < numbers.length; i++) {
        if (largest[smallest] > numbers[i]) continue;
        largest[smallest] = numbers[i];
        smallest = largest[0] < largest[1] ? 0 : 1;
    }
    return largest[0] + largest[1];
}

console.log(largestPairSum([10, 14, 2, 23, 19])); // 42 (23 + 19)
console.log(largestPairSum([99, 2, 2, 23, 19]));  // 122 (99 + 23)
console.log(largestPairSum([-10, -20, -30, -40])) // -30 (-10 + -20)

Answer №2

When working with a time complexity of O(n), as recommended by @VLAZ:

const findLargestPairSum = (arr) => {
  let firstLargest = -Infinity,
      secondLargest = -Infinity;
  
  for (let number of arr)
    if (number > firstLargest && secondLargest > -Infinity)
      firstLargest = number;
    else if (number > secondLargest)
      secondLargest = number;
      
  return firstLargest + secondLargest;
}

let tests = [
  findLargestPairSum([10, 14, 2, 23, 19]),
  findLargestPairSum([99, 2, 2, 23, 19]),
  findLargestPairSum([-10,-20,-30,-40]),
];

console.log(tests);
console.log("Nina's test:", findLargestPairSum([20, 50, 10, 1, 2]));

Answer №3

Your code has encountered three issues.

First off, the line

counter=numbersord[-1]+numbersord[-2]
is incorrect. Accessing a negative index in an array will result in undefined, as there is no element at that position. To retrieve elements from the end of an array, you should use arrayLength - negativeIndex:

const arr = ["a", "b", "c", "d", "e"];

console.log(arr[1]);
console.log(arr[2]);

console.log(arr[-1]);
console.log(arr[-2]);

console.log(arr[arr.length - 1]);
console.log(arr[arr.length - 2]);

Secondly, using numbers.sort() does not sort numbers correctly. It sorts them lexicographically rather than numerically, leading to unexpected results such as 10 < 2. For proper numeric sorting, refer to the link provided:

const arr = [1, 2, 10, 20]

arr.sort();
console.log("default (lexicographical) sort", arr);

arr.sort((a, b) => a - b);
console.log("ascending sort", arr);

arr.sort((a, b) => b - a);
console.log("descending sort", arr);

Lastly, the condition

if(numbersord[0] === -numbersord[0])
is unnecessary. The only number that equals its negative counterpart is zero:

console.log(0 === -0);
console.log(1 === -1);
console.log(42 === -42);
console.log(Infinity === -Infinity);
console.log(NaN === -NaN);

Instead of these checks, conducting a descending sort allows you to easily obtain the largest two items every time.

The revised code incorporating these changes looks like this:

function largestPairSum(numbers)
{
   let counter =0;
   //perform a descending sort
   let numbersord = numbers.sort((a, b) => b - a);
   
   //always take the first two items
   counter=numbersord[0]+numbersord[1]
       
   return counter
}

console.log(largestPairSum([10, 14, 2, 23, 19]))// --> 42 (i.e. sum of 23 and 19)
console.log(largestPairSum([99, 2, 2, 23, 19])) // --> 122 (i.e. sum of 99 and 23)
console.log(largestPairSum([-10,-20,-30,-40]))  // --> -30 (i.e sum of -10 and -20)

Answer №4

When dealing with the NaN type, it's important to understand that it is a number, even though it may appear confusing at first. This occurs when attempting to access elements in an array with indexes such as "-1" or "-2" which do not exist. To retrieve elements from the end of an array, you should utilize the following syntax:

arr[arr.length - 1] // returns the last element

Additionally,

let numbersord = numbers.sort(); // Note: sort() method modifies the original array, proceed with caution
numbersord[0] === -numbersord[0] // The result is true only for 0
// To check if a number is negative, use Math.abs()

The question arises - can an array contain both negative and positive elements simultaneously? In cases like [-10, -5, -2, 10], simply reversing the array will not yield the desired outcome (-15). Instead, consider using the reduce method as shown below:

function largestPairSum(arr) {
  const initialAcc = [-Infinity, -Infinity]
  const highestNumbers = arr.reduce((acc, rec)=> {
    if (rec <= acc[0]) return acc
    if (rec >= acc[1]) return [acc[1], rec]
    return [rec, acc[1]]
  },initialAcc)
  return highestNumbers[0] + highestNumbers[1]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building Next.js with a designated maximum number of processes/threads

I've uploaded a fresh Next.js app to the cloud server using npx create-next-app. However, when I try to run the build script, the server throws an error 'pthread-create: Resource temporarily unavailable'. { "name": "next&quo ...

Ways to prevent styles from being overridden by those specified in JavaScript

Some elements on my page have their style dynamically changed by JavaScript. However, I want one of them to maintain its static style without being overridden. Is there a way to specify that the style of this particular element should not be altered? Than ...

Middleware in Express can be executed more than once

I am encountering a frustrating issue where my middlewares are being called multiple times without explanation. Despite having written short and simple code while learning Express and Node, I cannot pinpoint the reason for this behavior. I find it confusin ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

Manually detecting changes in the query string using AngularJS

My AngularJS application includes an edit form with a routing URL like app/edit/:id. When I navigate to app/edit/5, I am able to edit the object with ID 5. However, if I manually change the URL to app/edit/6, the application loads the object with ID 6 in ...

Converting a jQuery DOM element into a string representation

Currently, I am working with a textarea that contains the contents of an HTML file. This textarea includes all elements of my HTML page such as doctype, head, html, etc. My goal is to save the content of the textarea into a DOM variable using $.parseHTML: ...

Problem with APIGEE search function

Encountered an issue while trying to retrieve an Apigee collection using the following code snippet: var my_pc_list = new Apigee.Collection( { "client":client, "type":"pc_pedidos", qs :{ql:"limit:50"} }); Error details: {"error":"query_parse","timestamp ...

Submitting data from a dropdown menu using Ajax in Struts 2: A step-by-step guide

I have a select tag with the s:select element inside a form. My goal is to send a post request to the specified action using Struts 2 json plugin. I do not have much knowledge in javascript or jquery. <s:form action="selectFileType" method="post" ...

What are some ways to personalize a scrollbar?

I am looking to customize the scrollbar within a div. I attempted to modify it using the code below, but I encountered difficulties when trying to change the scroll buttons and did not achieve my desired outcome. Additionally, this customization did not wo ...

Module for managing optional arguments in Node.js applications

I'm on the hunt for a Node.js module that can effectively manage and assign optional arguments. Let's consider a function signature like this: function foo(desc, opts, cb, extra, writable) { "desc" and "cb" are mandatory, while everything else ...

Retrieving information from an Angular service using a specified function

I have been working on accessing data from a method within a service that returns coordinates, which are used to make HTTP requests in my application. I have integrated my Leaflet code into the controller to be able to access the lat,lng coordinates for ...

I am unfamiliar with this scenario but I can utilize Axios, async/await, and TypeScript to navigate it

Having trouble creating a workflows list from an axios response Error: Argument of type 'Promise<unknown>' is not assignable to parameter of type 'SetStateAction<WorkflowForReactFlowProps[] | null>'. Here's the Axios c ...

Embed API allows users to showcase a variety of charts all on one page

I am trying to incorporate two google analytics timeline charts using the embed API on a single page. However, I am facing an issue where only one chart is appearing. The first chart should display bounce rate data and the second chart should display sessi ...

Using AJAX in JavaScript within an HTML document is a valuable skill to have

I have the following JavaScript function that I need to call the /print2 function without clicking any buttons. I attempted to use Ajax for this, but I am new to Ajax and JavaScript. Can you help me identify where the issue might be? Thank you... <scr ...

Updating of an Angular Directive within a nested Directive ceases once the inner Directive has been modified

Encountered a challenge with directives nested within each other in AngularJS. The issue is that both directives share the same property through a service and have an input to modify this property. The outer directive uses "transclude" to include the inner ...

Display a different string from an array at random, revealing each one gradually with a time delay

Looking for a way to display strings randomly without replacing one with another? I need a script that can shuffle words in a list and present them in a random order, with the ability to adjust the delay between each word. If you have a more effective code ...

Guide on building a Vue Js input name field with string-variable schema

I have a project using VueJs and I am looking to extract JavaScript variables to create hidden fields. My goal is to set the name of the field based on the index of the variable, following a zig-zag naming schema. For example: <input type="text" nam ...

Create a rectangle when the mouse is pressed down

Creating a zoomable and pannable canvas in Fabric.js was easy, but now I am facing an issue with accurately drawing a rectangle on each mousedown event. The problem arises when the canvas is transformed from its original state, making the coordinates inacc ...

"Trying to access jQuery .slide and .slideUp features, but unfortunately they are

I've created this script: $("#comments .comment .links").hide(); $("#comments .comment").hover( function() { $(".links", this).stop(true).slideDown(300); }, function() { $(".links", this).stop(true).slideUp(300); } ); However, I'm facin ...

VueJS: What is the easiest way to create a new instance of a div with just a click of a button?

Is there a way to create a function that will generate a new instance of a specific div (.container in the template) when a button (#addDiv) is clicked, with the button being the only visible element on the webpage initially? I have heard about using docum ...