imashutosh51

Best Time to Buy and Sell Stock III

Jan 28th, 2026
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. #here we will follow the same strategy like Best time to buy and sell stock II when first buy col=0,first sell col=1, second buy=2, second sell=3 as we are allowed to do 2 buy and 2 sell
  2.  
  3. def fun(arr,i,k,dp):
  4.     if i==len(arr) or k>=4: #k>=4 means when you used two transaction before reaching to the end of the array.
  5.         return 0
  6.     if dp[i][k]!=-1:
  7.         return dp[i][k]
  8.     if k%2==0: #means buy
  9.         ans=max(-arr[i]+ fun(arr,i+1,k+1,dp), fun(arr,i+1,k,dp) ) #buy or not buy,if buy your net amount will be -ve
  10.     else:
  11.         ans=max(arr[i]+fun(arr,i+1,k+1,dp), fun(arr,i+1,k,dp)) #sell or not sell, if sold you will get share selling amount
  12.     dp[i][k]=ans
  13.     return ans
  14.  
  15.  
  16. class Solution:
  17.     def maxProfit(self, prices: List[int]) -> int:
  18.         dp=[[-1,-1,-1,-1] for i in range(len(prices))]
  19.         return fun(prices,0,0,dp)
  20.        
Advertisement
Add Comment
Please, Sign In to add comment