728x90
반응형
LeetCode-121
Best Time to Buy and Sell Stock : 싸게 사서 비싸게 팔아라!
note : max(profit)
myAnswer
:::python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
len_prices = len(prices)
if len_prices < 2:
return 0
buy = prices[0]
profit = prices[1] - prices[0]
for i in range(1,len_prices):
sell = max(prices[i:])
if profit < sell-buy:
profit = sell - buy
buy = prices[i]
if profit < 0:
profit = 0
return profit
Result : Time Over-ms Memory: Over-mb
Answer
:::python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
min_price = sys.maxsize
for price in prices:
min_price = min(min_price, price)
profit = max(profit, price - min_price)
return profit
Result : 1102ms Memory: 25.1mb
반응형
'One step' 카테고리의 다른 글
[leetcode-21] Merge Two Sorted Lists (0) | 2023.03.12 |
---|---|
[leetcode 234] Palindrom Linked List (0) | 2023.03.11 |
[leetcode-238] Product of Array Except Self (0) | 2023.03.08 |
[leetcode-561] Array Partition (0) | 2023.03.07 |
[leetcode-15] Three Sum (0) | 2023.03.06 |