Skip to content

Commit ecc9423

Browse files
committed
fix: 성능은 비슷하나 코드를 간소화한 버전
1 parent 12a0147 commit ecc9423

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

best-time-to-buy-and-sell-stock/gyeo-ri.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
1+
"""
2+
[결과 요약]
3+
# 시도한 로직 수: 4
4+
1. if/else 문으로 분기 처리(시간: O(n) / 공간: O(1))
5+
-
6+
2. if문 대신 min / max를 계속 계산하는 로식
7+
- None 대신 float(inf)를 사용하여 None 검증 분기 제거
8+
- inf 사용을 위해서 마지막 return에 int() 타입 변환 필요
9+
- 성능은 1과 큰 차이 없으며 코드가 간소화
10+
"""
11+
12+
113
class Solution:
214
def maxProfit(self, prices: list[int]) -> int:
315
max_profit = 0
4-
buy_at = None
16+
min_price = float("inf")
517

618
for p in prices:
7-
if buy_at is None:
8-
buy_at = p
9-
elif buy_at > p:
10-
buy_at = p
11-
elif buy_at < p:
12-
max_profit = max(max_profit, p - buy_at)
19+
min_price = min(min_price, p)
20+
max_profit = max(max_profit, p - min_price)
1321

14-
return max_profit
22+
return int(max_profit)
1523

1624

1725
if __name__ == "__main__":
1826
test_cases = [
1927
([7, 1, 5, 3, 6, 4], 5),
2028
([7, 6, 4, 3, 1], 0),
2129
([2, 4, 1], 2),
30+
([1, 2, 4, 10000, 2, 1, 3], 9999),
2231
]
2332

2433
solution = Solution()

0 commit comments

Comments
 (0)