Electronics Shop: HackerRank Solution in Python
Solution in Python
def getMoneySpent(keyboards, drives, b): if min(keyboards) + min(drives) > b:
return -1 possibleBuys = [i+j for i in keyboards for j in drives if i+j<=b]
return max(possibleBuys)
Explanation
First we will consider the scenario where it is not possible to buy both items. If the sum of minimum element of keyboards list and minimum element of drives list is greater than the budget i.e b then it is not possible to buy both items so we return -1.
if min(keyboards) + min(drives) > b:
return -1
Now, we will use list comprehension to find all possible sum of elements of keyboards list and drives list such that it is less than or equal to b.
possibleBuys = [i+j for i in keyboards for j in drives if i+j <=b]
where i is an element in keyboards and j is an element in drives.
Consequently, possibleBuys will contain all the possible costs of computer keyboards and drives that can be bought with given budget.
Thus, the maximum element of possibleBuys list will be the cost of most expensive computer keyboard and USB drive that can be purchased with the given budget. We will return our answer.
return max(possibleBuys)