Skip to content

Commit 599a89d

Browse files
committed
The best time to buy and sell stock is added in DP section with test (TheAlgorithms#7104)
1 parent 24e3f5f commit 599a89d

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

dynamic_programming/best_time_to_buy_sell_stock.py

+28-4
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,23 @@
44
# comments: This program output the
55
# best time to buy and sell stock with fees
66
#############################
7-
import doctest
7+
from typing import List
88

99

1010
class Solution:
11-
def solve(self, prices, index, fee, buy, dp):
11+
def solve(
12+
self, prices: List[int], index: int, fee: int, buy: int, dp: List[List[int]]
13+
) -> int:
14+
"""
15+
Calculate the maximum profit with the given parameters.
16+
17+
:param prices: List of prices for each day.
18+
:param index: Current day index.
19+
:param fee: Transaction fee.
20+
:param buy: Buy or sell flag (1 for buy, 0 for sell).
21+
:param dp: Memoization table.
22+
:return: Maximum profit achievable.
23+
"""
1224
if index >= len(prices):
1325
return 0
1426
if dp[index][buy] != -1:
@@ -29,15 +41,25 @@ def solve(self, prices, index, fee, buy, dp):
2941
dp[index][buy] = profit
3042
return profit
3143

32-
def maxprofit(self, prices, fee):
44+
def maxprofit(self, prices: List[int], fee: int) -> int:
45+
"""
46+
Calculate the maximum profit achievable when buying and
47+
selling stocks with a fee.
48+
49+
:param prices: List of stock prices for each day.
50+
:param fee: Transaction fee.
51+
:return: Maximum profit achievable.
52+
"""
3353
n = len(prices)
3454
dp = [[-1] * 2 for _ in range(n)]
3555

3656
return self.solve(prices, 0, fee, 1, dp)
3757

3858

3959
def main():
40-
## This is the function for taking input and output ##
60+
"""
61+
This is the function for taking input and output.
62+
"""
4163
prices = list(map(int, input("Enter the list of prices: ").split()))
4264
fee = int(input("Enter the transaction fee: "))
4365

@@ -48,5 +70,7 @@ def main():
4870

4971

5072
if __name__ == "__main__":
73+
import doctest
74+
5175
doctest.testmod()
5276
main()

0 commit comments

Comments
 (0)