Computer >> Computer tutorials >  >> Programming >> Python

Best Time to Buy and Sell Stock III in Python


Suppose we have an array for which the ith element is representing the price of a given stock on day i. We have to devise an algorithm to find the maximum profit. We can complete at most two transactions. So if the given prices are [3,3,5,0,1,3,1,4], then the result will be 6, as we will buy on day 4 (price 0), then sell on day 6, (price 3), so profit is 3 – 0 = 3. Now but on day 7 (price 1), and sell on day 8 (price 4) so profit is 4 – 1 = 3.

To solve this, we will follow these steps −

  • n := size of s, m := size of t. Update s and t by concatenating blank spaces before them

  • Make one matrix of size (n + 1) x (m + 1)

  • set dp[0, 0] := 1, then set 1 for 0th column of all row, put 1

  • for i in range 1 to n

    • for j in range 1 to m

      • if s[i] = t[j], then

        • dp[i, j] := dp[i – 1, j – 1]

      • dp[i, j] := dp[i, j] + dp[i – 1, j]

  • return dp[n, m]

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def maxProfit(self, p):
      if not p:
         return 0
      n = len(p)
      dp = [0 for i in range(n)]
      ans = 0
      xmin = p[0]
      for i in range(1,n):
         xmin = min(xmin,p[i])
         dp[i] = max(dp[i],p[i]-xmin)
         ans = max(ans,dp[i])
      xmax = [0 for i in range(n)]
      xmax[-1] =p[-1]
      tempp = 0
      for i in range(n-2,-1,-1):
         xmax[i] = max(xmax[i+1],p[i])
      xmin = [p[-1],n]
      for i in range(n-2,-1,-1):
         tempp = max(tempp,xmax[i+1]-p[i+1])
         ans = max(ans,dp[i]+tempp)
      return ans
ob = Solution()
print(ob.maxProfit([3,3,5,0,1,3,1,4]))

Input

[3,3,5,0,1,3,1,4]

Output

6