Program to find maximum profit we can make by buying and selling stocks in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a list of stock prices of a company in chronological order, we have to find the maximum profit we could have made from buying and selling the stock. We must buy before selling, and we must wait one day after selling the stock before buying again.

So, if the input is like prices = [2, 6, 9, 4, 11], then the output will be 11, as we can buy at 2, then sell at 6, wait for a day, then buy at 4 and then sell at 11.

To solve this, we will follow these steps:

  • s := 0

  • b := -infinity

  • for i in range 0 to size of prices, do

    • temp := b

    • b := maximum of b and (s - prices[i])

    • if i is non-zero, then

      • s := maximum of s and (temp + prices[i - 1])

  • return maximum of s and (b + last element of prices)

Let us see the following implementation to get better understanding:

Example

 Live Demo

class Solution:
   def solve(self, prices):
      s = 0
      b = float("-inf")
      for i in range(len(prices)):
         temp = b
         b = max(b, s - prices[i])
         if i:
            s = max(s, temp + prices[i - 1])
      return max(s, b + prices[-1])

ob = Solution()
prices = [2, 6, 9, 4, 11]
print(ob.solve(prices))

Input

[2, 6, 9, 4, 11]

Output

11
raja
Published on 10-Nov-2020 07:34:52
Advertisements