배열 내에서 두 값의 차가 가장 큰 값을 찾는 로직
- tmp : 가장 최소인 값을 찾음
- answer : 차이가 최대인 것을 찾음
파이썬 내장함수인 min, max를 활용하여 배열을 하나씩 탐색하여 리스트 내 가장 차이가 큰 두 값의 차를 구한다.
def solution(prices):
INF = 1000000001;
tmp = INF
answer = -INF
for price in prices:
if tmp != INF:
answer = max(answer, price - tmp)
tmp = min(tmp, price)
return answer
prices1 = [1, 2, 3];
ret1 = solution(prices1);
print("solution 함수의 반환 값은", ret1, "입니다.")
prices2 = [3, 1];
ret2 = solution(prices2);
print("solution 함수의 반환 값은", ret2, "입니다.")
'Algorithm' 카테고리의 다른 글
[ 다익스트라 알고리즘] Dijkstra 기본 (0) | 2022.03.21 |
---|---|
[파이썬 힙] Heapq 사용법 (0) | 2022.03.21 |
[파이썬] 재귀함수, StackOverFlow 발생 이유 (0) | 2022.02.13 |
[코테 기본 암기] Python 소수 구하기 (0) | 2021.10.25 |
댓글