Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
Example
For inputArray = [3, 6, -2, -5, 7, 3]
, the output should beadjacentElementsProduct(inputArray) = 21
.
7
and 3
produce the largest product.
我的解答:
def adjacentElementsProduct(inputArray):
li = []
if len(inputArray) == 1:
return inputArray[0]
elif len(inputArray) == 2:
return inputArray[0]*inputArray[1]
else:
for i in range(len(inputArray)):
if i+2 <= len(inputArray)-1:
c_max = max(inputArray[i]*inputArray[i+1],inputArray[i+1]*inputArray[i+2])
li.append(c_max)
return max(li)
ret = adjacentElementsProduct([3, 6, -2, -5, 7, 3])
print(ret)
膜拜大神:
def adjacentElementsProduct(inputArray):
return max([inputArray[i] * inputArray[i+1] for i in range(len(inputArray)-1)])