Skip to content

Commit 9fd122f

Browse files
committed
solve Best Time to Buy and Sell Stock
1 parent 87a6cea commit 9fd122f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
# Straight Forward DP.
6+
#
7+
# Time: O(n). One Pass.
8+
# Space: O(1) additional space.
9+
#
10+
# [ 7, 1, 5, 3, 6, 4]
11+
# min_cost : inf, inf, 1, 1, 1, 1
12+
# profit_i : -inf, -inf, 4, 2, 5, 3
13+
# Max of profit_i is 5.
14+
def maxProfit(self, prices: List[int]) -> int:
15+
min_cost_before_i = float("inf")
16+
max_profit = 0
17+
for price in prices:
18+
max_profit = max(max_profit, price - min_cost_before_i)
19+
min_cost_before_i = min(min_cost_before_i, price)
20+
return max_profit
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import unittest
2+
3+
from best_time_to_buy_and_sell_stock import Solution
4+
5+
6+
class TestBestTimeToBuyAndSellStock(unittest.TestCase):
7+
def test_example_1(self):
8+
assert Solution().maxProfit(prices=[7, 1, 5, 3, 6, 4]) == 5
9+
10+
def test_example_2(self):
11+
assert Solution().maxProfit(prices=[]) == 0
12+
13+
def test_example_3(self):
14+
assert Solution().maxProfit(prices=[7, 6, 4, 3, 1]) == 0

0 commit comments

Comments
 (0)