imashutosh51

Maximum profits in stock

Jul 31st, 2022 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. '''
  2. Logic: we used a dp table whose row denotes the number of transactions and column denotes the stocks prices daywise.
  3. so dp[i][j] is equal to maximum profit acheived till jth day after i transactions.
  4.  
  5. using 0 transactions,no profit can be earned so 0th row will be filed with 0.
  6. using any number of transaction in one day only,no profit can be earned because stock
  7. price doesn't changing same day.
  8.  
  9. for eg i=2 and j=5
  10. now,using i transactions,and at jth day,maxium profit will be:
  11. either do i transaaction till j-1th day ie. dp[i][j-1]  
  12. or do i-1 transaction till day 0 and  last transaction or ith transaction between day 0 to jth day ie. dp[1][0]+arr[5]-arr[0]
  13. or do i-1 transaction till day 1 and last transaction or ith transaction between day 1 to jth day  ie. dp[1][1]+arr[5]-arr[1]
  14. .                                                                                                  ie. dp[1][2]+arr[5]-arr[2]
  15. .
  16. .
  17. or do i-1th transaction till j-1 day and last transaction or ith transaction between day j-1 to jth day ie. dp[1][4]+arr[5]-arr[4]
  18. so,arr[5] is common in above example ie. stock price of current day
  19. so max_val will store the value of maximum profit of i-1th transaction - stock price at that day so if we will add
  20. the stock price of jth day then we will have maximum of last transaction completed on jth day.
  21.  
  22. Maximum profit obtained till the jth day using at most i transactions.less than i transaction is also possible but each transaction means buy+sell both.
  23.  
  24. '''
  25. class Solution:
  26.     def maxProfit(self, k, n, arr):
  27.         dp = [[0] * 501 for _ in range(201)] #Maximum profit obtained till the jth day using at most i transactions.
  28.  
  29.         for i in range(1, k + 1):
  30.             max_val = float('-inf')
  31.  
  32.             for j in range(1, n):
  33.                 # update max_val if profit till last transaction - that day price
  34.                 max_val = max(max_val, dp[i - 1][j - 1] - arr[j - 1])
  35.  
  36.                 # check if selling today gives better profit, max_val+buying price of today & dp[i][j-1] don't do any transaction at all
  37.                 dp[i][j] = max(max_val + arr[j], dp[i][j - 1])
  38.  
  39.         return dp[k][n - 1]
Advertisement
Add Comment
Please, Sign In to add comment