Naive Solution: Maximum Pairwise Product

Naive solution for the Maximum Pairwise Product Problem.

We'll cover the following

Naive algorithm

A naive way to solve the Maximum Pairwise Product Problem is to go through all possible pairs of the input elements A[1...n]=[a1,...,an]A[1...n] = [a_1,...,a_n] and to find a pair of distinct elements with the largest product, as given in the following pseudocode.


 MaxPairwiseProductNaive(A[1...n])MaxPairwiseProductNaive(A[1 . . . n]):
  product0product \leftarrow 0
  for ii from 11 to nn:
       for jj from 11 to nn:
              if iji\neq j:
                     if product<A[i]A[j]product < A[i] \cdot A[j]:
                            productA[i]A[j]product \leftarrow A[i] \cdot A[j]
 return productproduct


This code can be optimized and made more compact as follows:


 MaxPairwiseProductNaive(A[1...n])MaxPairwiseProductNaive(A[1 . . . n]):
  product0product \leftarrow 0
  for ii from 11 to nn:
       for jj from i+1i+1 to nn:
              productmax(product,A[i]A[j])product \leftarrow max(product, A[i] \cdot A[j])
 return productproduct


Level up your interview prep. Join Educative to access 70+ hands-on prep courses.