- Related Questions & Answers
- Program to find maximum profit we can make by buying and selling stocks in Python?
- Best Time to Buy and Sell Stock in Python
- Program to find maximum profit after buying and selling stocks at most two times in python
- Best Time to Buy and Sell Stock II in Python
- Best Time to Buy and Sell Stock III in Python
- Program to find maximum profit we can get by buying and selling stocks with a fee in Python?
- Program to find minimum possible maximum value after k operations in python
- Program to find the maximum profit we can get by buying on stock market once in Python
- Program to find the maximum profit we can get by buying on stock market multiple times in Python
- Program to find maximum difference of adjacent values after deleting k numbers in python
- Best Time to Buy and Sell Stock IV in C++
- Program to find maximum value of k for which we can maintain safe distance in Python
- Maximum profit after buying and selling the stocks in C++
- Best Time to Buy and Sell Stock with Cooldown in C++
- Program to find minimum number of days to wait to make profit in python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

- Define a function dp() . This will take i, k, bought
- if i is same as size of prices or k is same as 0, then
- return 0

- if bought is true, then
- return maximum of (dp(i+1, k-1, False) + prices[i]) and dp(i+1, k, bought)

- otherwise,
- return maximum of (dp(i+1, k, True) - prices[i]) and dp(i + 1, k, bought)

- From the main method call dp(0, k, False) and return result

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

3

Advertisements