Best Time to Buy and Sell Stock - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import sys
def maxProfit(prices):
profit = 0 # 최대값
min_price = sys.maxsize # 최소값
for price in prices:
min_price = min(min_price, price)
profit = max(profit, price - min_price)
return profit
prices = [3, 10, 2, 2, 1, 15, 4, 20]
print(maxProfit(prices))
|
cs |
자기 자신을 빼는 경우는 0이 나오니 결과에 영향을 주지 않는다. 계속 for 문을 돌리면 된다.
'알고리즘 문제풀이 with 파이썬 > LeetCode' 카테고리의 다른 글
[스택] Remove Duplicate Letters (0) | 2021.09.13 |
---|---|
[스택] Valid Parentheses (0) | 2021.09.12 |
[배열] Product of Array Except Self (0) | 2021.09.11 |
[배열] Array Partition I (0) | 2021.09.10 |
[배열] 3Sum (0) | 2021.09.09 |