Suppose we have a list of numbers called nums that is representing the stock prices of a company in chronological order and we also have another value k, we have to find the maximum profit we can make from up to k buys and sells (We must buy before sell, and sell before buy).
So, if the input is like prices = [7, 3, 5, 2, 3] k = 2, then the output will be 3, as we can buy at 3, then sell at 5, again buy at 2, and sell at 3.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, prices, k): def dp(i, k, bought): if i == len(prices) or k == 0: return 0 if bought: return max(dp(i + 1, k - 1, False) + prices[i], dp(i + 1, k, bought)) else: return max(dp(i + 1, k, True) - prices[i], dp(i + 1, k, bought)) return dp(0, k, False) ob = Solution() prices = [7, 3, 5, 2, 3] k = 2 print(ob.solve(prices, k))
[7, 3, 5, 2, 3], 2