From 47038f6829925f60a9a06d5a42f0dc4155b2b246 Mon Sep 17 00:00:00 2001 From: rimogsu Date: Mon, 31 Aug 2026 22:45:51 +0900 Subject: [PATCH] 121 --- .../121. Best Time to Buy and Sell Stock.py" | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 "leetcode3/\353\263\200\354\247\200\355\230\221/v2/121. Best Time to Buy and Sell Stock.py" diff --git "a/leetcode3/\353\263\200\354\247\200\355\230\221/v2/121. Best Time to Buy and Sell Stock.py" "b/leetcode3/\353\263\200\354\247\200\355\230\221/v2/121. Best Time to Buy and Sell Stock.py" new file mode 100644 index 00000000..39590276 --- /dev/null +++ "b/leetcode3/\353\263\200\354\247\200\355\230\221/v2/121. Best Time to Buy and Sell Stock.py" @@ -0,0 +1,36 @@ + +''' +1. 아이디어 : +처음 가격부터 끝 가격까지 왼쪽에서 최소값, 오른쪽에서 최대값을 구한 후 최대값 - 최소값을 구한다. + +2. 시간복잡도 : +o(n) + +3. 자료구조/알고리즘 : +dp +''' + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + left = [] + right = [] + n = len(prices) + + tmp = 99999 + for price in prices: + if tmp > price: + left.append(price) + tmp = price + else: + left.append(tmp) + + tmp = -1 + for price in prices[::-1]: + if tmp < price: + right.append(price) + tmp = price + else: + right.append(tmp) + right = right[::-1] + + return max([right[i] - left[i] for i in range(n)]) \ No newline at end of file