Skip to content

Commit 200e74a

Browse files
authored
Merge pull request #5 from gyeo-ri/best-time-to-buy-and-sell-stock
Best time to buy and sell stock
2 parents 467eb00 + 5cf7923 commit 200e74a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
[๊ฒฐ๊ณผ ์š”์•ฝ]
3+
# ์‹œ๋„ํ•œ ๋กœ์ง ์ˆ˜: 2
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+
13+
class Solution:
14+
def maxProfit(self, prices: list[int]) -> int:
15+
max_profit = 0
16+
min_price = float("inf")
17+
18+
for p in prices:
19+
min_price = min(min_price, p)
20+
max_profit = max(max_profit, p - min_price)
21+
22+
return int(max_profit)
23+
24+
25+
if __name__ == "__main__":
26+
test_cases = [
27+
([7, 1, 5, 3, 6, 4], 5),
28+
([7, 6, 4, 3, 1], 0),
29+
([2, 4, 1], 2),
30+
([1, 2, 4, 10000, 2, 1, 3], 9999),
31+
]
32+
33+
solution = Solution()
34+
for idx, case_ in enumerate(test_cases):
35+
prices, answer = case_
36+
result = solution.maxProfit(prices)
37+
assert (
38+
answer == result
39+
), f"Test Case {idx} Failed: Expected {answer}, Got {result}"

0 commit comments

Comments
ย (0)