Skip to content

Commit 29d2f61

Browse files
committed
- Best Time to Buy And Sell Stock #221
1 parent fcc0136 commit 29d2f61

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List
2+
class Solution:
3+
"""
4+
- Time Complexity: O(n), n = len(prices)
5+
- Space Complexity: O(1)
6+
"""
7+
def maxProfit(self, prices: List[int]) -> int:
8+
min_price = float("inf")
9+
max_profit = 0
10+
11+
for price in prices:
12+
min_price = min(min_price, price)
13+
max_profit = max(max_profit, price - min_price)
14+
15+
return max_profit
16+
17+
tc = [
18+
([7,1,5,3,6,4], 5),
19+
([7,6,4,3,1], 0)
20+
]
21+
22+
for i, (prices, e) in enumerate(tc, 1):
23+
sol = Solution()
24+
r = sol.maxProfit(prices)
25+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)