How I Solved Hacker Rank Challenge, ‘Electronics Shop’

Hi Everyone,

Today I will be going over how I solved Hacker Rank Challenge, Electronic Shop, using JavaScript.

The Objective: A person wants to determine the most expensive computer keyboard and USB drive that can be purchased with a give budget. Given price lists for keyboards and USB drives and a budget, find the cost to buy them. If it is not possible to buy both items, return -1.

The parameters that is provided is keyboards, drives, and b (budget). I created a variable maxEquip to track the most expensive equipment within the budget provided and set it to -1, the value returned if none of the equipment(1 keyboard, 1 drive) is within budget.

Next I created variables k and d and set them to zero. This will be used for our for loops.

I first create a for loop for the array of keyboard prices. I want to take each price in the array and add it to each individual drive to see if the total is within budget.

This requires adding an internal iterator to loop through the array of drive prices. In this for loop, I use an if statement that adds a keyboard price to the cost of a drive. If it’s within budget and greater than our most expensive equipment tracked in variable maxEquip than store this new amount in our maxEquip variable.

This will allow me to return the most expensive equipment or return -1 if none of these requirements are met. This is my final code:

function getMoneySpent(keyboards, drives, b) {
* Write your code here.
let maxEquip = -1;
let k = 0;
let d = 0;
for (k=0; k < keyboards.length; k++) { for (d=0; d < drives.length; d++) {
if (keyboards[k] + drives[d] <= b &&
keyboards[k] + drives[d] > maxEquip)

{ maxEquip = keyboards[k] + drives[d]; }}}
return maxEquip}

Hope everyone enjoyed this blog. Please let me know your thoughts. Until next time!