Problem

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.


Input/Output

  • [input] array.integer inputArray

    An array of integers containing at least two elements.

    Guaranteed constraints:
    2 ≤ inputArray.length ≤ 10,
    -1000 ≤ inputArray[i] ≤ 1000.

  • [output] integer

    The largest product of adjacent elements.


Solution

def adjacentElementsProduct(inputArray):     return max([inputArray[i] * inputArray[i + 1] for i in range(len(inputArray) - 1)])

     *Point : List Comprehension

Step 1. integer 로 구성된 배열을 0부터 배열의 길이 -1 까지 for문을 활용하여 탐색합니다. (Index Error를 방지하기 위해 -1까지 탐색)

Step 2. i 번 째와 i+1 번 째를 곱한 값을 리스트에 저장합니다.

Step 3. max() 함수를 활용하여 반환된 리스트에서의 최대값을 추출합니다.


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] almostIncreasingSequence  (0) 2018.02.08
[Algorithm] makeArrayConsecutive2  (0) 2018.02.08
[Algorithm] shapeArea  (0) 2018.02.08
[Algorithm] checkPalindrome  (0) 2018.02.07
[Algorithm] centuryFromYear  (0) 2018.02.07

+ Recent posts