We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
O(m log m + n log n) Solution in Python
The logic is the same as ryanfehr18' solution, but this will help those who have trouble understanding as to why the complexity of the loop block is O(m+n).
Both keyboards and drives are sorted in ascending order. For keyboards, we move from left to right, for drives from right to left.
We match the cheapest keyboard with most expensive drive, if it works, update the cur_max and try to pick up a costly keyboard.
Else, we try to pick up a cheaper drive.
defgetMoneySpent(k,d,b):## Write your code here.#keyboards=sorted(k)drives=sorted(d)m=0n=len(drives)-1cur_max=-1whilem<len(keyboards)andn>=0:cur_sum=keyboards[m]+drives[n]ifcur_sum<=b:cur_max=max(cur_max,cur_sum)m+=1#tryexpensivekeyboardelse:n-=1#trycheaperdrivereturncur_max
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Variable Sized Arrays
You are viewing a single comment's thread. Return to all comments →
O(m log m + n log n) Solution in Python The logic is the same as ryanfehr18' solution, but this will help those who have trouble understanding as to why the complexity of the loop block is O(m+n). Both keyboards and drives are sorted in ascending order. For keyboards, we move from left to right, for drives from right to left. We match the cheapest keyboard with most expensive drive, if it works, update the cur_max and try to pick up a costly keyboard. Else, we try to pick up a cheaper drive.