*알고리즘 스터디에 참여하면서 Blind 75 LeetCode Questions 목록에 있는 문제를 풀이합니다.
문제: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
풀이:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
maxProfit = 0
minPurchase = prices[0]
for i in range(1, len(prices)):
maxProfit = max(maxProfit, prices[i] - minPurchase)
minPurchase = min(minPurchase, prices[i])
return maxProfit
주식의 최저값을 첫번째 인자를 넣어주고, 배열을 하나씩 조회하면서
(현재 가격 - 최저값)과 수익값 중, 최대값을 수익값으로 보고 바꿔준다.
현재 가격과 수익값 중 최저값을 수익값으로 보고 바꿔준다.
'📒 Tech Note > 알고리즘 & 자료구조' 카테고리의 다른 글
[LeetCode] 53. Maximum Subarray (0) | 2022.09.03 |
---|---|
[LeetCode] 238. Product of Array Except Self (0) | 2022.08.24 |
[LeetCode] 217. Contains Duplicate (0) | 2022.08.24 |
[LeetCode] 1. Two Sum (0) | 2022.08.20 |
[선형 자료구조] 1. Array (0) | 2022.08.14 |