Skip to content

Commit 072312b

Browse files
committed
The best time to buy and sell stock is added in DP section with annotations and test cases(TheAlgorithms#7104)
1 parent 9382a88 commit 072312b

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

dynamic_programming/best_time_to_buy_sell_stock.py

+30-4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@
77
# from typing import list
88

99

10+
import unittest
11+
12+
# from typing import list
13+
14+
1015
class Solution:
1116
def solve(
1217
self, prices: list[int], index: int, fee: int, buy: int, dp: list[list[int]]
@@ -43,19 +48,40 @@ def solve(
4348

4449
def maxprofit(self, prices: list[int], fee: int) -> int:
4550
"""
46-
Calculate the maximum profit achievable when buying and
47-
selling stocks with a fee.
48-
51+
Calculate the maximum profit achievable when buying
52+
and selling stocks with a fee.
4953
:param prices: list of stock prices for each day.
5054
:param fee: Transaction fee.
5155
:return: Maximum profit achievable.
56+
Example:
57+
>>> s = Solution()
58+
>>> s.maxprofit([1, 3, 2, 8, 4, 9], 2)
59+
8
60+
>>> s.maxprofit([1, 4, 3, 6, 8, 2, 7], 3)
61+
6
5262
"""
5363
n = len(prices)
5464
dp = [[-1] * 2 for _ in range(n)]
5565

5666
return self.solve(prices, 0, fee, 1, dp)
5767

5868

69+
class TestSolution(unittest.TestCase):
70+
def test_maxprofit(self):
71+
s = Solution()
72+
73+
# Test case 1: Example input
74+
# Test case 1: Example input
75+
prices1 = [1, 3, 2, 8, 4, 9]
76+
fee1 = 2
77+
assert s.maxprofit(prices1, fee1) == 8 # Use assert instead of self.assertEqual
78+
79+
# Test case 2: Another example
80+
prices2 = [1, 4, 3, 6, 8, 2, 7]
81+
fee2 = 3
82+
assert s.maxprofit(prices2, fee2) == 6
83+
84+
5985
def main():
6086
"""
6187
This is the function for taking input and output.
@@ -73,4 +99,4 @@ def main():
7399
import doctest
74100

75101
doctest.testmod()
76-
main()
102+
unittest.main()

0 commit comments

Comments
 (0)