Here's a time-linear solution (after sorting):
def maximize(a, b, lim): a.sort(reverse=True) b.sort() found = False best = 0 j = 0 for i in xrange(len(a)): while j < len(b) and a[i] * b[j] < lim: found = True if a[i]*b[j] > best: best, n1, n2 = a[i] * b[j], a[i], b[j] j += 1 return found and (best, n1, n2)
Simply put:
- start with the highest and lowest of each list
- while their product is smaller than the target, promote a small item
- Once the product is larger than your goal, advance the large item until it drops below.
Thus, you can go through each list only once. He will return False if he cannot find anything small enough, otherwise he will return the product and the pair that created it.
Output Example:
a = [2, 5, 4, 3, 6] b = [8, 1, 5, 4] maximize(a, b, 2)
tzaman
source share