Python
파이썬 알고리즘 인터뷰 - 12. 주식을 사고팔기 가장 좋은 시점
s코딩초보s
2022. 1. 15. 14:34
<--- 리트코드 121. Best Time to Buy and Self Stock --->
# 문제: 한 번의 거래로 낼 수 있는 최대 이익을 산출하라.
입력
[7, 1, 5, 3, 6, 4] |
출력
5 |
# 풀이
1. 브루트 포스로 계산
1
2
3
4
5
6
7
8
9
10
|
def max_profit(price):
max_price = 0
for i in range(0, len(price) - 1):
for j in range(i + 1, len(price)):
max_price = max(price[j] - price[i], max_price)
return max_price
price = [7, 1, 5, 3, 6, 4]
print(max_profit(price))
|
cs |
2. 저점과 현재 값과의 차이 계산
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import sys
def max_profit(price):
profit = 0
min_price = sys.maxsize
for i in price:
min_price = min(i, min_price)
profit = max(i - min_price, profit)
return profit
price = [7, 1, 5, 3, 6, 4]
print(max_profit(price))
|
cs |