🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Python Example Code: Find the pair of adjacent elements that has the largest product


# Given an array of integers, find the pair of adjacent elements
# that has the largest product and return that product.
# Approach 1: (Brute Force) - Check all the pairs in the list and then return the maximum pair
# Time Complexity: O(N^2)
def adjacentElementProductBF(inputArray):
largestProduct = -999999
# for sanity check, assert if array contains at least 2 elements
if len(inputArray) < 2:
print("No pairs exists")
return -1
for i in range(0, len(inputArray)):
for j in range(i+1, len(inputArray)):
currentProduct = inputArray[i]*inputArray[j]
if currentProduct > largestProduct:
largestProduct = currentProduct
return largestProduct
# Approach 2: (Sort & Pick Last Pair) - Sort the list and then pick the last two numbers
# Caveat: All elements must be positive
# Time Complexity: O(Nlog(N))
def adjacentElementsProductSort(inputArray):
size = len(inputArray)
if size < 2:
print("No Pairs exist")
return -1
sortedArray = sorted(inputArray)
return sortedArray[-1] * sortedArray[-2]
def adjacentElementsProduct(inputArray):
length = int(len(inputArray))
maxm = inputArray[0]*inputArray[1]
product = 1
for i in range(1, length-1):
product = inputArray[i]*inputArray[i+1]
if product>maxm:
maxm = product
return maxm
# print(adjacentElementsProduct([3,6,7,5]))
print(adjacentElementsProduct([3, 6, -2, -5, 7, 3]))
#Alternate solution
#return max([inputArray[i]*inputArray[i+1] for i in range(0, int(len(inputArray)-1))])
Subscribe
Notify of
guest


0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x