Program to find maximum profit we can make after k Buy and Sell in python

PythonServer Side ProgrammingProgramming

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 −

Example 

Live Demo

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))

Input

[7, 3, 5, 2, 3], 2

Output

3
raja
Published on 03-Dec-2020 05:33:46
Advertisements