Computer Science/알고리즘 문제풀이
[codesignal][python] 1. adjacentElementsProduct
MLra
2020. 12. 26. 02:09
Coding Tests and Assessments for Technical Hiring | CodeSignal
Learn how you can go beyond resumes in technical hiring with a state-of-the-art assessment platform and advanced coding tests
codesignal.com
level : easy
Question:
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.
My answer:
def adjacentElementsProduct(inputArray):
return max(a * b for a, b in zip(inputArray[:-1], inputArray[1:]))
- [1,2,3,4,5,6]이 inputArray라면, inputArray[:-1] 은 [1,2,3,4,5], inputArray[1:] 은 [2.3.4.5.6]
- zip함수를 사용해 [(1,2),(2,3),(3,4),(4,5),(5,6)] 으로 만들어줌
- max함수 사용
reference code:
def adjacentElementsProduct(inputArray):
return max([inputArray[i] * inputArray[i+1] for i in range(len(inputArray)-1)])
- 인덱스를 사용해서 inputArray의 0번째부터 마지막 전 원소까지 돌면서 자신과 자기 뒤에 있는 원소의 곱을 탐색
- max함수 사용 (동일)