Skip to content

Commit 3b318d6

Browse files
committed
"Best Time to Buy and Sell Stock II" solution
1 parent dd7bd40 commit 3b318d6

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def maxProfit(self, prices: list[int]) -> int:
3+
assert prices
4+
5+
n = len(prices)
6+
total_profit = 0
7+
last = prices[-1]
8+
9+
for i in range(n - 1, -1, -1):
10+
if prices[i] < last:
11+
total_profit += last - prices[i]
12+
last = prices[i]
13+
14+
return total_profit
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import pytest
2+
3+
from src.best_time_to_buy_and_sell_stock_ii import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
"prices,expected_profit",
8+
(
9+
([7, 1, 5, 3, 6, 4], 7),
10+
([1, 2, 3, 4, 5], 4),
11+
([7, 6, 4, 3, 1], 0),
12+
),
13+
)
14+
def test_solution(prices, expected_profit):
15+
assert Solution().maxProfit(prices) == expected_profit

0 commit comments

Comments
 (0)