Discovering the most cost-effective combination algorithm

Looking for two numbers, P and Q, in a given array N with at least 5 items where 0 < P < Q < N - 1.

Consider the following array:

const N = [1, 9, 4, 5, 8];
  • If P = 1 , Q = 2 , then the cost is N[P] + N[Q] = N[1] + N[2] = 9 + 4 = 13
  • If P = 1, Q = 3 , then the cost is N[P] + N[Q] = N[1] + N[3] = 9 + 5 = 14
  • If P = 2, Q = 3 , then the cost is N[P] + N[Q] = N[2] + N[3] = 4 + 5 = 9

The combination with the minimum cost is P = 2 and Q = 3.

Here's a solution that can potentially be improved for better time complexity:

function solution(N) {
  // since  0 < P < Q < N - 1
  const sliced = N.slice(1, N.length - 1);
  const sorted = sliced.sort((a, b) => a - b);

  // the minimum should be from the start since we have sorted the array
  const P = 0;
  const Q = 1;

  return getCost(P, Q, sorted);
}

function getCost(P, Q, N) {
  return N[P] + N[Q];
}

// output should be 9
console.log(solution([1, 9, 4, 5, 8]))

In a best-case scenario, the time complexity is O(n log(n)) due to the sort operation. However, are there ways to improve it to O(n)?

Thank you for your assistance!

Answer №1

function findTwoSmallestNumbers(arr) {
  let [smallest, secondSmallest] = [arr[1], arr[2]]
  
  for (let i = 3; i < arr.length - 1; i++) {
    const element = arr[i]
    if (element < smallest && element < secondSmallest) {
      [smallest, secondSmallest] = [Math.min(smallest, secondSmallest), element] 
    } else if (element < smallest) {
      [smallest, secondSmallest] = [secondSmallest, element]
    } else if (element < secondSmallest) {
      secondSmallest = element
    }
  }
  return smallest + secondSmallest
}

This solution operates in linear time complexity O(n) and constant space complexity O(1). It also ensures that the smaller index element is stored in smallest, which may be useful in scenarios where index information is important.

The algorithm logic is straightforward, but I believe there might be more optimized ways to implement this in JavaScript. My JS skills are a bit rusty as I haven't practiced it recently.

Answer №2

How do you feel about this proposed solution?

function findSumOfTwoSmallestNums([_, ...nums]) {
  nums.pop()
  nums.sort((a, b) => a - b);

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

// expected result is 9
console.log(findSumOfTwoSmallestNums([1, 9, 4, 5, 8]))

The concept remains the same as you described earlier - just implemented using another technique available in JavaScript.

Answer №3

My analysis leads me to believe that this algorithm is O(n):

const findTwoSmallest = (arr) => {
  // Find the smallest number that's not at either end
  let index = 1;
  let firstMin = arr[1];
  for(let i = 2; i < arr.length-1; i++) {
    if(arr[i] < firstMin) {
      index = i;
      firstMin = arr[i];
    }
  }
  // Find the second smallest number that's not at either end
  let secondMin = Infinity;
  for(let i = 1; i < arr.length-1; i++) {
    if(i == index) continue;
    if(arr[i] < secondMin) secondMin = arr[i];
  }
  return firstMin + secondMin;
}

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

Navigating through an ajax-based webpage entirely with selenium webdriver

I have attempted to scroll a page entirely using the following code: var scrollToBottom = function() { window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight)); }; window.on ...

Creating Web Components using JavaScript on the fly

I tried to create web components directly from JavaScript, but I encountered an issue where the public constructor could not be found. Here's a basic example to illustrate the situation: The HTML Template: <polymer-element name="wc-foo" construct ...

Is there a navigation feature in VueJS that functions similarly to React Router?

I am currently working on enhancing the navigation experience of an existing vueJS application that utilizes Vue Router. When working with React, I typically structure breadcrumbs in the following manner: <Breadcrumbs> <Route path="/users&q ...

JavaScript allows for selecting individual IDs by their corresponding numbers

Looking to retrieve numerical IDs <div class="user-view"> <div class="show_user_div"> <div class="disp"> <a href="/profile/name1/">name1</a><br /> <span id="show_a_3"> <a id="ref_show(3)">Show Details</ ...

Dark opaque background image with Material-UI styling

I'm enclosing all the widgets within a CardMedia component, and adding an image. return ( <CardMedia image={bg} className={classes.bg}> <main className={classes.content}> <div className={classes.toolbar} /> <Grid contai ...

Framer Motion causes a crash in a Next.js application with the error message: "Unable to find named export 'useId'"

I am encountering an error in my Next.js app that I can't seem to trace back to its source. Strangely, the code triggering the error is not something I wrote myself. error - file:///Users/cheq/Desktop/cheqo/node_modules/framer-motion/dist/es/component ...

Cover the entire screen with numerous DIV elements

Situation: I am currently tackling a web design project that involves filling the entire screen with 60px x 60px DIVs. These DIVs act as tiles on a virtual wall, each changing color randomly when hovered over. Issue: The challenge arises when the monitor ...

How are jQuery.ajax and XMLHttpRequest different from each other?

My goal is to fetch and run the script contained in a file named "example.js" using an AJAX request. Suppose the content of example.js looks like this: const greetings = { hello: "Hello", goodBye: "Good bye" } console.log(greetings.hello) In anot ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

What is the proper way to define the font slant as "slnt" in NextJS development?

My preference is to use the font style slnt -8 for Inter. When importing with a URL through SCSS, I am able to specify slnt -8 as follows: @import url("https://fonts.googleapis.com/css2?family=Inter:slnt,wght@-8,100..900&display=swap"); Unf ...

Steps to retrieve an array from AJAX request and save it to a JavaScript variable

How can I retrieve the 'this.responseText' array from this function and assign it to a variable named 'teacherIDList'? Any suggestions? var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readySt ...

Automatically close an element when you click on a different element

Hello everyone! I need some help again. I'm working on a script that displays an overlay when a menu item is clicked. Within this menu, there is a modal contact form with a close icon or anchor that should appear when clicked. My goal is to have the o ...

Failure to Reach AngularJS ng-click Function

When trying to add a new product to the product list, I am facing an issue. The products load correctly but the ng-click function is not being triggered. (The alert I set up in the addProduct function is not appearing). HTML <div ng-controller="Produc ...

Using MeanJS to assign a Mongoose object reference to an array in Angular

Having an issue with MeanJS and using the $update function of the $resource service in Angular provided by MeanJS. Here is a basic outline of my problem: Mongoose schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Lotion ...

Tips for embedding Javascript code within the window.write() function

I have a JavaScript function that opens a new window to display an image specified in the data variable. I want the new window to close when the user clicks anywhere on it. I've tried inserting some JavaScript code within window.write() but it doesn&a ...

The return type of a server-side component in NextJS 14 when it is asynchronous

When using NextJS 14, I encountered a problem with the example provided in the documentation. The example is within the Page component, typically typed as NextPage. However, this type does not support the use of async await server components. In my case, ...

Integrate CSS and Javascript Plugins into your Ruby on Rails application

I am utilizing an HTML, CSS, and JS template to design the interface for my Rails application. Within this template, there are several plug-ins that are required in both CSS and JS formats. I have stored these plug-ins within the "/assets/plugins/" directo ...

What causes immediately invoked functions within event handlers to be executed before the event is triggered?

let b = (function maria() { alert("ee"); })(); * this code runs as soon as the page loads * <button onclick="b">Click me</button> * this code only runs when button is clicked * <button onclick="alert('ee')">Click m ...

React filtering displaying array elements that appear single time

I've been working on this React code to filter and search items based on user input. The issue I'm facing is that when I delete the text input and try again, the filtered items disappear and don't show up unless I reload the page. I'm c ...

Maintain the selected bootstrap tab even after the page is refreshed, even when the content is loaded dynamically

I am currently facing an issue with loading tabs using Angular. Whenever a tab is clicked, the id is saved to localStorage. Now, I want to programmatically click on the same tab using jQuery when the page refreshes. However, since the DOM element for the ...