Code Signal_练习题_adjacentElementsProduct

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.

我的解答:

 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)])
上一篇:Java提高篇——JVM加载class文件的原理机制


下一篇:软硬链接、文件删除原理、linux中的三种时间、chkconfig优化