JavaScript challenge at an electronics store coding competition

Hello, I recently attempted a code challenge but unfortunately only passed 9 out of the 16 tests. I am seeking feedback on what may be going wrong in my code. The problem link can be found here:

function getMoneySpent(keyboards, drives, budget) {
    let comboArray = [];
    let lenOfKeyboards = keyboards.length;
    let lenOfDrives = drives.length;
    let j = drives.length;
    comboArray = keyboards.slice(0);
    for (let number of drives) {
        comboArray.push(number);
    }
    return (findMaxCombo(comboArray, lenOfKeyboards, budget));
}


function findMaxCombo(comboArray, lenOfKeyboards, budget) {
    let result = [];
    let j = lenOfKeyboards;
    for (let i = 0; i < lenOfKeyboards; i++) {
        if (comboArray[i] >= budget || comboArray[j] >= budget) return -1;
        if (comboArray[i] + comboArray[j] < budget) {
            result.push(comboArray[i] + comboArray[j]);
        }
        i--;
        j++;
        if (j == comboArray.length) {
            i++;
            j = lenOfKeyboards;
        }
    }
    if (result.length == 0) return -1;
    return result.sort()[result.length - 1];
}

Answer №1

Given the constraints provided in the problem statement, a simpler solution suffices.

Here is the outlined Algorithm:

  1. Set a variable maxValue to -1.
  2. Iterate through two for loops over drives and keyboards, calculating the sum of each drive with each keyboard.
  3. Within the loops, verify if the sum of drive + keyboard is within Monica's budget and record the maximum value obtained from any combination in maxValue.
  4. Upon completion, return the value of maxValue.

Code Snippet:-

function calculateMaxBudget(keyboards, drives, budget) {
    let maxValue = -1;
    for (let drive of drives) {
        for(let keyboard of keyboards) {
            let cost = drive + keyboard;
            if(cost > maxValue && cost <= budget) {
                maxValue = cost;
            }
        }
    }
    return maxValue;
}

Overall Time complexity - O(n^2).

Hope this explanation serves you well!

Answer №2

When your code returns -1, it means there may not be a solution due to a specific line of code:

if (arr[i] >= m || arr[j] >= m) return -1;

Even if one item exceeds the budget, remember that there could still be cheaper options available. Existing solutions in result should also be considered, or they may be found in a later iteration.

I find it puzzling why there is a need to create a merged array of both input arrays. This step does not appear to offer any advantages.

By sorting the input arrays, a two-pointer system can be utilized to determine which item to move based on whether the current sum is within the limits or exceeds them:

function getMoneySpent(keyboards, drives, b) {
    keyboards = [...keyboards].sort((a, b) => b - a) // descending
    drives = [...drives].sort((a, b) => a - b); // ascending
    let k = keyboards.length - 1; // cheapest
    let d = drives.length - 1; // most expensive
    let maxSum = -1;
    while (d >= 0 && k >= 0) {
        let sum = keyboards[k] + drives[d];
        if (sum === b) return b;
        if (sum < b) {
            if (sum > maxSum) maxSum = sum;
            k--; // will increase sum 
        } else {
            d--; // will decrease sum
        }
    }
    return maxSum;
}

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

The JavaScript file fails to load when it is invoked within the <script> tag in HTML

I'm relatively new to this and I'm grappling with why my script isn't loading from the HTML. This is my primary hurdle at the moment. Next, I'm looking to obtain a list of the available COM ports and send data to a port that is ready. ...

When working with VueJS and Vuex, using the splice method to replace an item (object) in an array stored in Vuex does not trigger a re-render of the

I have an array of records. Each record consists of an object with _id (mongo id), title, and value (value is an object with amount and currency). When displaying the list of records using v-for, the ':key' for each item in the list is set to th ...

I am looking to create a route with parameters in Next.js, as well as without any parameters

I am working on a NEXTJS project and utilizing SSR for data fetching. However, I am trying to implement the following scenario: When users land on the "/" route, they should be presented with a random product detail page. But if they search for a specific ...

Generating fresh objects to establish a Many-to-Many connection with Sequelize

I am currently utilizing NodeJS, Express, Sequelize, and PostgreSQL in my project. Within my application, I have defined two models: a "User" model and a "Social" model. My goal is to establish a many-to-many relationship where a user can be associated wi ...

A guide to resolving the error "Unable to find 'require' in vuejs"

I am currently working on a project using vuejs and firebase. I encountered an issue while trying to import firestore. When I accessed my page, I saw this error message in the console: ReferenceError: require is not defined I attempted to place the import ...

What is the best way to refresh a single component in my application without causing the other components to reload?

I've been working on a review application with Vue.js that fetches random facts from an API (https://uselessfacts.jsph.pl/random.json?language=en) and allows users to provide feedback through radio buttons and text inputs. Once submitted, the feedback ...

Tips for accessing user input in JavaScript functions

In my ASP.NET code, I have created a dynamic image button and panel. Here is the code: Panel panBlocks = new Panel(); panBlocks.ID = "PanBlockQuestionID" + recordcount.ToString(); panBlocks.Width = 1300; panBlocks.Height = 50; panBlocks.BackColor = Color. ...

Unable to maintain checkbox state after page reload in React

I am currently working on creating a to-do list application using React and Material UI. Everything is functioning well except for the checkbox state. I am storing each to-do as an object in an array called todoList in local storage, like this: todoList i ...

Position the div so that it is aligned with the top offset of another element

My question is straightforward. I have a div1 element with a variable offset().top that adjusts based on other elements on the page. I am looking to add an absolutely positioned div next to it, which should have the same absolute top value. This can be ach ...

Unable to expand Bootstrap navbar due to collapsing issue

I recently implemented a collapsed navbar on my website using bootstrap. However, I'm facing an issue where it does not open when clicking on the hamburger menu. After researching various solutions for this problem and trying them out, none of them s ...

Removing single quotes and replacing them with spaces when passing data from JavaScript to MySQL

I'm currently focused on JavaScript using Hapi.js in my role at the company. My main task involves retrieving data from MongoDB and transferring it to a MySQL database. The challenge arises when dealing with data that contains single quotes within th ...

guide on utilizing the Thingspeak API with jQuery AJAX

I am attempting to call the Thingspeak REST API and display the value on an HTML page. However, I am encountering an issue where the value is showing as undefined. Here is the code snippet I am using: <script type="text/javascript"> $(document) ...

Button for copying URL and pasting it to clipboard available for use on desktop, iOS, and Android platforms using JavaScript

Is it feasible to use JavaScript/jQuery to copy the current URL and paste it into the clipboard using pure JS? Specifically, I am targeting phone users, like those with iPhones running Safari. I want to create a button that can automatically retrieve the ...

What is the method for displaying an array in JavaScript?

When a user clicks the value 3 input box, three input boxes will appear where they can enter values. However, when trying to submit the array, no elements are printed and an error message "Element is not defined" appears. var arr = [0]; function get_va ...

Keep the link underlined until a different button is pressed

I need help with a webpage that displays a list of partners organized by categories. When clicking on sidebar categories, the link remains underlined. However, if you click anywhere else on the page, the link becomes inactive. CSS: button:hover { t ...

unable to transfer Vuex store information to the graph

Currently, I am facing an issue with passing my vuex store data into my apexcharts graph. Despite my efforts, it seems like the data is not being displayed correctly. Can anyone provide guidance on what I might be doing wrong? My main objective is to updat ...

Delete an item from an array based on its index within the props

I am attempting to remove a specific value by its index in the props array that was passed from another component. const updatedData = [...this.props.data].splice([...this.props.data].indexOf(oldData), 1); const {tableData, ...application} = oldData; this ...

Interactive image sliders in a Netflix-inspired style with live previews on hover, fully compatible with Bootstrap framework

I'm looking for suggestions on Twitter Bootstrap compatible jquery plugins that can create a Netflix-style continuously scrolling image carousel with mouse-over functionality. I've tried the carousel included in the Bootstrap JS library, but it r ...

Setting the state for an element in React after it has been mounted - a step-by-step guide

My React application features a user data form with a notification message that appears after submitting the form. The notification can be either a success or fail message, with the latter potentially containing multiple error types. I handle the error typ ...

Exploring Methods to Access External Iframes Using PHP or JavaScript

I need assistance tracking my package that was sent through the local post service. The tracking information can be found at this link: . Using the tracking number RF166699170SK, I should be able to locate the package. However, when I attempt to retrieve ...