Online Judge/LeetCode
[LeetCode][Python] 121. Best Time to Buy and Sell Stock
vince joe
2024. 9. 8. 21:44
- 문제 링크: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
- 난이도: Easy
일 별 주가가 주어지는데, 매수 & 매도를 한번씩 했을 때 가장 큰 이익이 얼마인지 구하는 문제다
매도 -> 매수는 안된다.
배열을 한번 순회하는데, 최저가를 계속 업데이트하면서 매매차익 max 값을 구하면 된다
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ret = 0
lowest = prices[0]
for p in prices:
if p < lowest:
lowest = p
ret = max(ret, p - lowest)
return ret
반응형