Skip to content

Commit b11d8e7

Browse files
committed
feat: best time to buy and sell stock 풀이추가
1 parent 11f97b1 commit b11d8e7

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class Solution:
2+
def maxProfit(self, prices: list[int]) -> int:
3+
if not prices:
4+
return 0
5+
6+
min_price = prices[0]
7+
max_profit = 0
8+
9+
for price in prices[1:]:
10+
max_profit = max(max_profit, price - min_price)
11+
min_price = min(min_price, price)
12+
13+
return max_profit
14+
15+
16+
"""
17+
================================================================================
18+
풀이 과정
19+
================================================================================
20+
21+
[문제 이해]
22+
────────────────────────────────────────────────────────────────────────────────
23+
1. 주어진 배열 prices가 있고 prices[i]는 i날의 특정 주식 가격
24+
2. 하나의 주식을 사기 위해 하루를 선택하고, 그 주식을 팔기 위해 미래의 다른 날을 선택
25+
3. 이 거래에서 얻을 수 있는 최대 이익을 반환
26+
4. 이익을 얻을 수 없다면 0을 반환
27+
28+
예시 1: [7, 1, 5, 3, 6, 4] → 5
29+
2일에 사서 5일에 팔면 → 6 - 1 = 5가 나오면서 가장 큰 값
30+
31+
예시 2: [7, 6, 4, 3, 1] → 0
32+
아무런 이익이 있는 날이 없음
33+
34+
35+
[1차 시도] Brute Force 접근
36+
────────────────────────────────────────────────────────────────────────────────
37+
5. 모든 (구매일, 판매일) 쌍을 비교해서 최대 이익 찾기
38+
6. 이중 반복문으로 구현
39+
40+
profit = 0
41+
for i in range(len(prices)):
42+
for j in range(i+1, len(prices)):
43+
profit = max(profit, prices[j] - prices[i])
44+
return profit
45+
46+
7. 시간복잡도: O(n²) → 시간 초과 발생!
47+
48+
49+
[2차 시도] 최적화 방법 고민
50+
────────────────────────────────────────────────────────────────────────────────
51+
8. 그러면 다른 풀이 방식이 필요할 것 같은데
52+
9. 조건을 정리:
53+
- 이전 값이 다음 값보다 크면 버려도 된다
54+
- 이전 값이 다음 값보다 작으면 해당 값을 기록한다
55+
- 이미 기록된게 있으면 비교해본다
56+
57+
[7, 1, 5, 9, 3, 6, 4]
58+
min을 추적하면서 현재가 - min 중 최대값을 찾으면 됨!
59+
60+
61+
[최종 구현] Kadane's Algorithm 변형
62+
────────────────────────────────────────────────────────────────────────────────
63+
10. 한 번의 순회로 최소 구매가와 최대 이익을 동시에 추적
64+
11. 각 시점에서:
65+
- 현재가 - 최소가 = 지금 팔면 얻는 이익
66+
- 최대 이익 갱신
67+
- 최소가 갱신
68+
69+
min_price = prices[0]
70+
max_profit = 0
71+
72+
for price in prices[1:]:
73+
max_profit = max(max_profit, price - min_price)
74+
min_price = min(min_price, price)
75+
76+
12. 시간복잡도: O(n) - 한 번의 순회
77+
13. 공간복잡도: O(1) - 상수 공간만 사용
78+
"""

0 commit comments

Comments
 (0)