Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Method 1:
- '''
- so you have only two option, if you buy now, next index either sell or not sell(may be you be sell later).
- and if you sold now, you will buy next or buy later.
- buy=True means you already bough and vice versa
- 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.
- oth col for the buy and 1st col for the sell.
- 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.
- '''
- def fun(arr,i,buy,dp):
- if i>=len(arr):
- return 0
- if buy:
- if dp[i][0]!=-1:
- return dp[i][0]
- if not buy:
- if dp[i][1]!=-1:
- return dp[i][1]
- if buy:
- ans=max(-arr[i]+ fun(arr,i+1,False,dp), fun(arr,i+1,True,dp))
- else:
- ans=max(arr[i]+fun(arr,i+1,True,dp), fun(arr,i+1,False,dp))
- if buy:
- dp[i][0]=ans
- else:
- dp[i][1]=ans
- return ans
- class Solution:
- def maxProfit(self, prices: List[int]) -> int:
- dp=[[-1,-1] for i in range(len(prices))]
- return fun(prices,0,True,dp)
- #Method 2: Most optimised and simple approach
- class Solution:
- def maxProfit(self, prices: List[int]) -> int:
- ans=0
- for i in range(1,len(prices)):
- if prices[i-1]<prices[i]:
- ans+=prices[i]-prices[i-1]
- return ans
Advertisement
Add Comment
Please, Sign In to add comment