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 be
adjacentElementsProduct(inputArray) = 21
. 7
and 3
produce the largest product.
我的解答:
1 def adjacentElementsProduct(inputArray): 2 li = [] 3 if len(inputArray) == 1: 4 return inputArray[0] 5 elif len(inputArray) == 2: 6 return inputArray[0]*inputArray[1] 7 else: 8 for i in range(len(inputArray)): 9 if i+2 <= len(inputArray)-1:10 c_max = max(inputArray[i]*inputArray[i+1],inputArray[i+1]*inputArray[i+2])11 li.append(c_max)12 return max(li)13 ret = adjacentElementsProduct([3, 6, -2, -5, 7, 3])14 print(ret)
膜拜大神:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
def adjacentElementsProduct(inputArray): return max([inputArray[i] * inputArray[i+1] for i in range(len(inputArray)-1)])