Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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
- def fun(arr,i,k,dp):
- if i==len(arr) or k>=4: #k>=4 means when you used two transaction before reaching to the end of the array.
- return 0
- if dp[i][k]!=-1:
- return dp[i][k]
- if k%2==0: #means buy
- 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
- else:
- 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
- dp[i][k]=ans
- return ans
- class Solution:
- def maxProfit(self, prices: List[int]) -> int:
- dp=[[-1,-1,-1,-1] for i in range(len(prices))]
- return fun(prices,0,0,dp)
Advertisement
Add Comment
Please, Sign In to add comment