1- #Given an array of integers,
2- #find the pair of adjacent elements
3- #that has the largest product and
4- #return that product.
1+ # Given an array of integers, find the pair of adjacent elements
2+ # that has the largest product and return that product.
3+
4+ # Approach 1: (Brute Force) - Check all the pairs in the list and then return the maximum pair
5+ # Time Complexity: O(N^2)
6+
7+ def adjacentElementProductBF (inputArray ):
8+ largestProduct = - 999999
9+
10+ # for sanity check, assert if array contains at least 2 elements
11+ if len (inputArray ) < 2 :
12+ print ("No pairs exists" )
13+ return - 1
14+
15+ for i in range (0 , len (inputArray )):
16+ for j in range (i + 1 , len (inputArray )):
17+ currentProduct = inputArray [i ]* inputArray [j ]
18+
19+ if currentProduct > largestProduct :
20+ largestProduct = currentProduct
21+
22+ return largestProduct
23+
24+ # Approach 2: (Sort & Pick Last Pair) - Sort the list and then pick the last two numbers
25+ # Caveat: All elements must be positive
26+ # Time Complexity: O(Nlog(N))
27+
28+ def adjacentElementsProductSort (inputArray ):
29+ size = len (inputArray )
30+
31+ if size < 2 :
32+ print ("No Pairs exist" )
33+ return - 1
34+
35+ sortedArray = sorted (inputArray )
36+ return sortedArray [- 1 ] * sortedArray [- 2 ]
37+
538
639def adjacentElementsProduct (inputArray ):
740
@@ -24,11 +57,3 @@ def adjacentElementsProduct(inputArray):
2457
2558#Alternate solution
2659#return max([inputArray[i]*inputArray[i+1] for i in range(0, int(len(inputArray)-1))])
27-
28-
29-
30-
31-
32-
33-
34-
0 commit comments