Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. # Traders-Max-Profit
  2.  
  3. ![Trade](https://change-wm.com/wp-content/uploads/2018/07/678789789.jpg)
  4.  
  5. ## Another problem within the Dynamic Programming paradigm
  6.  
  7. ### Statement:
  8.  
  9. Given stock prices calculate the maximum possible profit a trader could make with at most two transactions in one day.
  10.  
  11. **Example:**
  12.  
  13. *Stock prices of one day:*
  14.  
  15. prices[] = {75, 4, 25, 20, 60, 45}
  16.  
  17. *Expected Output:*
  18.  
  19. Maximum possible profit: 61
  20.  
  21. **Explanation:**
  22.  
  23. Suppose the trader initially had **n** dollars.
  24.  
  25. Buy the stock with the price 4, sell it at a price 25 -> one transaction
  26.  
  27. We now have: n-4+25 = n+21
  28.  
  29. But at a price 20, sell at 60 -> second transaction
  30.  
  31. At this step we have: - 20 + 60.
  32.  
  33. So in total: n-4+25-20-60 = n + 21 + 40 = n + 61. We are adding 61 to the initial amount he had, so he made a profit of 61.
  34.  
  35. ### Theses:
  36.  
  37. 1) **We can make one transaction only after another is done.**
  38.  
  39. 2) **As in real world the time throughout the traders day is linear.** *Yeah, and?*
  40. Consider this example array: {40, 5, 80, 20, 60). Suppose the traders working hours starts at 9:00 am and that the first stock (40) is available to be bought at that time. Similarly his day, for example, ends at 17:00 pm and the last stock is available at that hour. Stocks inbetween, obviously, could be operated with in the hours between the start of the day and the end. For example stock with the price 80, say, at 15:00 pm. That means if he buys at first hour the 40-price stock and then sells it at the last hour at a price 60 he then can't do any other stock operations. The day has ended and the maximum profit he has made is n-40+60 -> 20. (But he could have made a profit of 115)
  41.  
  42. ### Solution:
  43.  
  44. 1) Create an array with size **n**. Where **n** is the size of input array (prices). Lets name it *profit*.
  45.  
  46. - This array will hold all intermediate results of possible transactions (sell - buy) that could be made.
  47.  
  48. 2) Create a variable **max** and assing it's value as last element of the input array.
  49.  
  50. - This variable will hold the maximum price at which we can sell with one transaction.
  51.  
  52. 3) Iterate over the input array once and do the following:
  53. - Step 1: *if element at current index is greater than max -> change **max** to it*
  54.  
  55. - Step 2: *at the current index of the **profit** array assing maximum of (previous result, maximum - element at current index of the input array) = max(**profit[i + 1]**, **max - prices[i]**)*
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement