Well, this is a challenge in Hackerrank called Electonic Shop and this is my code, it works to a certain test. When the inputs increment the time of compilation gets more time. So I need to sum for every number in one array with the other numbers for the second array.
function getMoneySpent(keyboards, drives, b) { let purchase = []; let result = -1; for(let i = 0; i < keyboards.length; i++) { for(let j = 0; j < drives.length; j++) { if((keyboards[i] + drives[j]) <= b) { purchase.push(keyboards[i] + drives[j]); result = Math.max(...purchase); } } } return result; } console.log(getMoneySpent([4], [5], 5)); // Should return -1 console.log(getMoneySpent([3, 1], [5, 2 ,8], 10)); //Should return 9 console.log(getMoneySpent([40, 50, 60], [5, 8, 12], 60)) // Should return 58 I don't know how to make it more efficient.
https://stackoverflow.com/questions/66727874/how-would-i-sum-for-every-number-in-each-array-each-other March 21, 2021 at 08:49AM
没有评论:
发表评论