728x90
1132 ms
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit, min_price = 0, float("inf")
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
min_price를 min으로 업데이트 시켜주면서 element순서대로 작은 값으로 update
max_price를 max로 업데이트 시켜주면서 price-min_price(현재 포함해서 그전까지 가장 작은 값, 만약 현재랑 같다면 0이 됨)
이런 문제는 다음에는 무조건 바로 해결해야됨.
출처: github.com/jiapengwen/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock.py
944ms
class Solution:
def maxProfit(self, prices: List[int]) -> int:
low = prices[0]
maxProfit = 0
for price in prices:
if price < low:
low = price
if price - low > maxProfit:
maxProfit = price - low
return maxProfit
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Valid Palindrome python (regex, filter, isalnum) (0) | 2021.04.01 |
---|---|
[LeetCode] Best Time to Buy and Sell Stock II python (greedy) (0) | 2021.04.01 |
[LeetCode] Pascal's Triangle 파이썬 (+Pascal's Triangle II) (0) | 2021.04.01 |
[LeetCode] Path Sum 파이썬 (0) | 2021.04.01 |
[LeetCode] Minimum Depth of Binary Tree 파이썬 (recursion) (0) | 2021.04.01 |
댓글