From 12c3ee7ab9108722519117bb7404d8f1ef49a63f Mon Sep 17 00:00:00 2001 From: nkey Date: Mon, 13 Jul 2026 15:29:48 +0900 Subject: [PATCH] =?UTF-8?q?easy/dp=20121=20=EC=84=B1=EA=B3=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- easy/dp/121.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 easy/dp/121.py diff --git a/easy/dp/121.py b/easy/dp/121.py new file mode 100644 index 0000000..b8ec250 --- /dev/null +++ b/easy/dp/121.py @@ -0,0 +1,23 @@ +# Best Time to Buy and Sell Stock + +class Solution: + def maxProfit(self, prices: list[int]) -> int: + dp = [0] * len(prices) + max_price = prices[-1] + for i in range(len(prices)-2, -1, -1): + dp[i] = max_price - prices[i] + max_price = max(max_price, prices[i]) + + return max(dp) + +""" +걸린 시간: 15분 + +복잡도: n길이의 dp 테이블을 뒤에서부터 한번만 순회하면서 채우기 때문에 시간복잡도는 O(n)이다. +n길이의 dp 테이블을 만들기 때문에 공간복잡도도 O(n)이다. + +해설: 산 것은 미래에만 팔 수 있기 때문에 미래가 없는 것부터 미래를 하나씩 늘려가면서 미래의 최대 값과 수익의 최대값을 갱신하면 되겠다고 생각했다. +dp[i]는 i번째 날에 사는 경우 얻을 수 있는 이익의 최대값이다. i번째 날에 샀을 때는 지금까지 오면서 price가 가장 컸던 날에 팔면 된다. + +사실 전체 날짜에 대한 정보 기록 없이 뒤에서 앞으로 가면서 지금까지의 최대 price와 profit만 기억해두면 공간복잡도를 O(1)로 줄일 수 있다. +""" \ No newline at end of file