I have two lists made of numbers(integers); both have 2 million unique elements.
I want to find number a from list 1 and b from list 2, that –
1)a*b should be maximized.
2)a*b has to be smaller than certain limit.
here’s what I came up with:
maxpq = 0
nums = sorted(nums, reverse=True)
nums2 = sorted(nums2, reverse=True)
for p in nums:
n = p*dropwhile(lambda q: p*q>sqr, nums2).next()
if n>maxpq:
maxpq=n
print maxpq
any suggestions?
edit : my method is too slow. It would take more than one day.
Here’s a linear-time solution (after sorting):
Simply put:
This way, you’re guaranteed to go through each list only once. It’ll return
Falseif it couldn’t find anything small enough, otherwise it’ll return the product and the pair that produced it.Sample output: