Skip to content

Commit ff62989

Browse files
committed
Best Time to Buy and Sell Stock
1 parent 365c8e4 commit ff62989

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
121. Best Time to Buy and Sell Stock
3+
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
4+
5+
문제: 주식 가격 배열이 μ£Όμ–΄μ§ˆ λ•Œ, ν•œ 번 사고 ν•œ 번 νŒ”μ•„μ„œ 얻을 수 μžˆλŠ” μ΅œλŒ€ 이읡을 κ΅¬ν•˜λΌ.
6+
(λ§€μˆ˜λŠ” 맀도보닀 μ•žμ„  λ‚ μ§œμ—¬μ•Ό 함)
7+
8+
μ˜ˆμ‹œ:
9+
Input: prices = [7, 1, 5, 3, 6, 4]
10+
Output: 5 (1일에 μ‚¬μ„œ 4일에 νŒ”λ©΄ 6-1=5)
11+
"""
12+
13+
from typing import List
14+
15+
16+
# =============================================================================
17+
# 풀이 1: 브루트 포슀 (Brute Force)
18+
# =============================================================================
19+
# 아이디어: λͺ¨λ“  (맀수일, 맀도일) 쑰합을 ν™•μΈν•˜μ—¬ μ΅œλŒ€ 이읡을 μ°ΎλŠ”λ‹€.
20+
# μ‹œκ°„ λ³΅μž‘λ„: O(nΒ²) - 이쀑 반볡문
21+
# 곡간 λ³΅μž‘λ„: O(1)
22+
# κ²°κ³Ό: Time Limit Exceeded (μ‹œκ°„ 초과)
23+
# =============================================================================
24+
class Solution:
25+
def maxProfit(self, prices: List[int]) -> int:
26+
result = 0
27+
28+
# i: 맀수일 (0 ~ n-2)
29+
for i in range(len(prices) - 1):
30+
# r: 맀도일 (i+1 ~ n-1), 맀수일 이후여야 함
31+
for r in range(i + 1, len(prices)):
32+
# ν˜„μž¬ μ‘°ν•©μ˜ 이읡 = 맀도가 - λ§€μˆ˜κ°€
33+
profit = prices[r] - prices[i]
34+
result = max(result, profit)
35+
36+
return result
37+
38+
39+
# =============================================================================
40+
# 풀이 2: ν•œ 번 순회 (One Pass) - μ΅œμ ν™”
41+
# =============================================================================
42+
# 아이디어: 배열을 μˆœνšŒν•˜λ©΄μ„œ "μ§€κΈˆκΉŒμ§€μ˜ μ΅œμ†Œ λ§€μˆ˜κ°€"λ₯Ό μΆ”μ ν•œλ‹€.
43+
# 각 λ‚ μ§œμ—μ„œ ν˜„μž¬ κ°€κ²©μœΌλ‘œ νŒ”μ•˜μ„ λ•Œμ˜ 이읡을 κ³„μ‚°ν•˜κ³  μ΅œλŒ€κ°’μ„ κ°±μ‹ ν•œλ‹€.
44+
#
45+
# 핡심 톡찰:
46+
# - νŠΉμ • λ‚ μ§œμ— νŒ” λ•Œ μ΅œλŒ€ 이읡 = ν˜„μž¬κ°€κ²© - (μ΄μ „κΉŒμ§€μ˜ μ΅œμ†Œκ°€κ²©)
47+
# - λ”°λΌμ„œ μ΅œμ†Œ κ°€κ²©λ§Œ μΆ”μ ν•˜λ©΄ O(n)에 ν•΄κ²° κ°€λŠ₯
48+
#
49+
# μ‹œκ°„ λ³΅μž‘λ„: O(n) - ν•œ 번 순회
50+
# 곡간 λ³΅μž‘λ„: O(1)
51+
# =============================================================================
52+
class Solution:
53+
def maxProfit(self, prices: List[int]) -> int:
54+
max_profit = 0 # μ΅œλŒ€ 이읡
55+
min_price = prices[0] # μ§€κΈˆκΉŒμ§€μ˜ μ΅œμ†Œ λ§€μˆ˜κ°€
56+
57+
# 1일차뢀터 순회 (0μΌμ°¨λŠ” min_price μ΄ˆκΈ°κ°’)
58+
for price in prices[1:]:
59+
# 였늘 νŒ”μ•˜μ„ λ•Œμ˜ 이읡 계산
60+
profit = price - min_price
61+
# μ΅œλŒ€ 이읡 κ°±μ‹ 
62+
max_profit = max(max_profit, profit)
63+
# μ΅œμ†Œ λ§€μˆ˜κ°€ κ°±μ‹  (더 μ‹Ό 날이 있으면 μ—…λ°μ΄νŠΈ)
64+
min_price = min(min_price, price)
65+
66+
return max_profit
67+
68+

0 commit comments

Comments
Β (0)