import sys
class Solution:
def maxProfit(self, prices: List[int]) -> int:
lowest = sys.maxsize
best_p = 0 # 최대 이득 물어보는거니까 최소가 0
for i in range(len(prices)-1):
if prices[i] < lowest:
lowest = prices[i]
sub = prices[i+1] - lowest
if best_p < sub:
best_p = sub
return best_p
Runtime : 976 ms
Memory : 25.1 MB
import sys
class Solution:
def maxProfit(self, prices: List[int]) -> int:
lowest = sys.maxsize
profit = 0 # 최대 이득 물어보는거니까 최소가 0
for price in prices:
lowest = min(price, lowest)
profit = max(price - lowest ,profit)
return profit
Runtime : 1143 ms
Memory : 24.9 MB
첫 번째와 성능에 별 차이는 없지만 더 간결하게 작성 가능한 방법이다.
그냥 현재 시점에 대해서만 min 구하고 max 구하면 되는데 생각을 못했다
왜냐면 어차피 현재 시점에서 lowest 갱신돼도 profit은 0이 되니까 문제 없고 당연한 것이었다
더 나은 코드 추가해서 수정 업로드 예정