imashutosh51

Best Time to buy and sell stock II

Jan 28th, 2026 (edited)
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. #Method 1:
  2. '''
  3. so you have only two option, if you buy now, next index either sell or not sell(may be you be sell later).
  4. and if you sold now, you will buy next or buy later.
  5. buy=True means you already bough and vice versa
  6. when you buy something, you subtract the money as you gave some money,once you sell, you get the money back with profit,so profit will be remaining only.
  7.  
  8. oth col for the buy and 1st col for the sell.
  9. There might be case when you bought the share but reached at the end of the array-> in that scenerio you net amount will be -ve because it only bought and there are case also when you didn't buy, so no buy will return 0 where buy will return -ve value so no buy will be preferred.
  10. '''
  11. def fun(arr,i,buy,dp):
  12.     if i>=len(arr):
  13.         return 0
  14.     if buy:
  15.         if dp[i][0]!=-1:
  16.             return dp[i][0]
  17.     if not buy:
  18.         if dp[i][1]!=-1:
  19.             return dp[i][1]
  20.     if buy:
  21.         ans=max(-arr[i]+ fun(arr,i+1,False,dp), fun(arr,i+1,True,dp))
  22.     else:
  23.         ans=max(arr[i]+fun(arr,i+1,True,dp), fun(arr,i+1,False,dp))
  24.     if buy:
  25.         dp[i][0]=ans
  26.     else:
  27.         dp[i][1]=ans
  28.     return ans
  29.  
  30. class Solution:
  31.     def maxProfit(self, prices: List[int]) -> int:
  32.         dp=[[-1,-1] for i in range(len(prices))]
  33.         return fun(prices,0,True,dp)
  34.  
  35. #Method 2: Most optimised and simple approach
  36. class Solution:
  37.     def maxProfit(self, prices: List[int]) -> int:
  38.         ans=0
  39.         for i in range(1,len(prices)):
  40.             if prices[i-1]<prices[i]:
  41.                 ans+=prices[i]-prices[i-1]
  42.         return ans
  43.        
Advertisement
Add Comment
Please, Sign In to add comment