Skip to content

Instantly share code, notes, and snippets.

@zmaupin
Created October 9, 2019 02:15
Show Gist options
  • Select an option

  • Save zmaupin/a63c1e12fe308d3ad6616599de57fa7e to your computer and use it in GitHub Desktop.

Select an option

Save zmaupin/a63c1e12fe308d3ad6616599de57fa7e to your computer and use it in GitHub Desktop.
Maximum Pairwise Product Algorithm
# maximum pairwise product
# find the maximum product of two distinct numbers in a sequence of
# non-negative integers
# input: sequence of non-negative integers
# output: maximum value that can be obtained by multiplying two different
# elements from the sequence
import random
def maximum_pairwise_product(a):
product = 0
n = len(a)
for i in range(n):
for j in range(i + 1, n):
product = max(product, a[i] * a[j])
return product
def maximum_pairwise_product_fast(a):
n = len(a)
max_index1 = 0
for i in range(n):
if a[i] > a[max_index1]:
max_index1 = i
if max_index1 == 0:
max_index2 = 1
else:
max_index2 = 0
for i in range(n):
if i != max_index1 and a[i] > a[max_index2]:
max_index2 = i
return a[max_index1] * a[max_index2]
def generate_array():
n = random.randint(2, 10000)
a = []
while n > 0:
a.append(random.randint(0, 100000))
n -= 1
return a
def stress_test(a):
while True:
a = generate_array()
# print(a)
slow = maximum_pairwise_product(a)
fast = maximum_pairwise_product_fast(a)
if slow == fast:
print("OK")
else:
print("slow {0} does not equal fast {1}", slow, fast)
break
a = generate_array()
stress_test(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment