# LeetCode 123. Best Time to Buy and Sell Stock III

Problem:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Solution:

Do it DP front and back.

```public class Solution {
int[] pre;
int[] post;

public int maxProfit(int[] prices) {
if (prices.length < 2) return 0;
pre = new int[prices.length];
post = new int[prices.length];

int min = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < min) min = prices[i];
pre[i] = prices[i] - min > pre[i-1] ? prices[i] - min : pre[i-1];
}
int max = prices[prices.length - 1];
for (int i = prices.length - 2; i >= 0; i--) {
if (prices[i] > max) max = prices[i];
post[i] = max - prices[i] > post[i+1] ? max - prices[i] : post[i+1];
}

int profit = 0;
for (int i = 0; i < prices.length; i++) {
int p = pre[i] + post[i];
if (p > profit) profit = p;
}
return profit;
}
}
```

## 71 thoughts on “LeetCode 123. Best Time to Buy and Sell Stock III”

1. Today, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a forty foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is completely off topic but I had to share it with someone!

2. 大部份曾經生育或經歷更年期的女性都會面臨私密深處及外觀鬆弛問題，不單會影響自信心和伴侶的親密體驗，更有機會造成容易積菌及尿滲等健康問題。全港首部 Venus Fiore閨密儀 RF射頻 私密緊緻療程 專門針對私密各處包括陰道、陰唇及陰阜的專用治療頭，全面改善鬆弛問題；每個治療頭均採用一次性即棄治療蓋，確保衛生。還有ATC自動控溫綜合系統，讓療程的治療溫度被有效監控，療程自然更安全、更有效達至預期效果。全港首部 Venus Fiore閨密儀 RF射頻 私密緊緻療程Venus Fiore集中為女性私密之處提供最到位的呵護，專注重整陰道健康、收緊鬆弛陰唇和改善陰阜肥大問題。關鍵在於Venus Concept的王牌─糅合多極射頻與磁力脈衝的(ＭP)2磁頻專利技術，發揮提升細胞活躍度、重塑同時增加膠原蛋白、刺激毛細血管新生等作用，達至調整陰道濕潤度、pH值的效果，更重要的是顯著改善陰道彈性，使其回復年輕狀態。

3. I simply want to mention I’m very new to weblog and seriously enjoyed you’re website. Probably I’m planning to bookmark your site . You certainly have remarkable stories. Regards for revealing your blog site.

4. THREE 【POINT MAKEUP】星燦煥采眼影霜 Alchemist-Twist For Eye的商品介紹 THREE,POINT MAKEUP,星燦煥采眼影霜 Alchemist-Twist For Eye

5. Restylane乃一系列用於美顏的長效透明質酸產品。 Restylane療程能有效撫平皺紋、美化臉型輪廓及唇部，並可改善膚質及肌膚的彈性。Restylane透明質酸作用原理 Restylane透明質酸均以非動物來源的透明質酸作為原料，獨有的NASHA™專利技術研製而成。微量Restylane透明質酸凝膠到皮膚中，可以讓您的面部肌膚恢復豐盈飽滿。 Restylane透明質酸中的透明質酸與人體內的天然透明質酸十分相似，使用前無需進行皮膚測試，引起過敏反應的機率亦極低。

6. CHANEL 香奈兒 【完美粉底系列】雙效輕亮粉霜SPF15的商品介紹 CHANEL 香奈兒,完美粉底系列,雙效輕亮粉霜SPF15

7. Aw, i thought this was an extremely good post. In notion I must invest writing like that moreover – taking time and actual effort to have a excellent article… but what things can I say… I procrastinate alot through no means find a way to get something done.

8. SCOTCH & SODA女裝系列　橫越美洲之旅 – STYLE-TIPS.COM Scotch & Soda旗下的Maison Scotch女裝系列，今季…

9. 推薦好用的「定妝」網友評鑑排行榜一覽 網友評鑑排行榜 網友用過推薦最好用的定妝網友評鑑排行榜，這裡有網友們，最近六個月的美妝品排行榜，No.1~No.10名

10. CLINIQUE 倩碧線上購物官網。瀏覽Clinique倩碧官方網站，了解更多線上購物、護膚、彩粧、香氛及禮品詳情。通過過敏性測試，百分百不含香料。

11. 眾星雲集第72屆威尼斯影展　服裝線條簡約流暢 – STYLE-TIPS.COM 第72屆威尼斯影展眾星雲集，不少女星都以線條簡約而流暢的晚裝出席，當中憑藉電影《…

13. After looking into a number of the articles on your web page, I truly like your way of writing a blog. I book-marked it to my bookmark webpage list and will be checking back in the near future. Please visit my website too and tell me what you think.

14. Louis van Gaal exchanged a telling look with assistant manager Ryan Giggs after Javier Hernandez failed to score his first Manchester United goal in more than a year against Club Bruges. Javier Hernandez misses penalty and five-yard sitter… as Manchester United manager Louis van Gaal exchanges telling look with assistant Ryan Giggs

15. Many thanks for this article. I’d also like to say that it can end up being hard when you find yourself in school and simply starting out to initiate a long credit history. There are many students who are merely trying to live and have an extended or favourable credit history is often a difficult thing to have.

16. Hello there, I found your website by way of Google whilst looking for a similar matter, your website got here up, it seems great. I have bookmarked it in my google bookmarks.

17. Howdy! I simply would like to give you a big thumbs up for your great information you have got right here on this post. I will be returning to your blog for more soon.

18. Hi, i think that i saw you visited my site so i came to return the choose?.I am attempting to find issues to enhance my website!I guess its adequate to use a few of your ideas!!

19. Helpful Blog! We appeared to be just discussing there are lots screwy outcomes at the issue you now purely changed my very own belief. Thank you really significantly a perfect write-up

20. ?TKOHUB? Manny Pacquiao vs Shane Mosley Fight Video HL Manny Pacquiao vs Shane Mosley Fight Video HL | TKOHUB? – tkohub

21. Hey there! I simply wish to offer you a big thumbs up for the great info you have right here on this post. I’ll be coming back to your website for more soon.

22. Hi, i believe that i saw you visited my website so i came to go back the choose?.I’m attempting to in finding issues to enhance my site!I guess its adequate to make use of some of your ideas!!

23. Hello there! I just would like to give you a huge thumbs up for the great information you have got here on this post. I’ll be coming back to your website for more soon.

24. Hello there, I discovered your website by way of Google while searching for a comparable matter, your site got here up, it looks good. I have bookmarked it in my google bookmarks.

25. Hi there, I found your web site via Google at the same time as looking for a similar topic, your web site came up, it seems to be great. I have bookmarked it in my google bookmarks.

26. Hey there! I just want to give you a huge thumbs up for the excellent info you have got right here on this post. I’ll be coming back to your website for more soon.

27. Hello there, I found your web site by means of Google at the same time as searching for a similar topic, your site got here up, it looks good. I’ve bookmarked it in my google bookmarks.

28. Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam feedback? If so how do you stop it, any plugin or anything you can recommend? I get so much lately it’s driving me crazy so any support is very much appreciated.

29. What’s Going down i’m new to this, I stumbled upon this I’ve discovered It positively useful and it has aided me out loads. I hope to contribute & assist other users like its helped me. Great job.

30. My brother suggested I might like this blog. He was totally right. This post truly made my day. You cann’t imagine just how much time I had spent for this info! Thanks!

31. Hello, i feel that i saw you visited my weblog thus i came to return the choose?.I’m trying to in finding things to improve my web site!I suppose its adequate to use some of your ideas!!

32. Hello, i think that i noticed you visited my web site thus i got here to return the want?.I’m attempting to find things to enhance my web site!I guess its good enough to use some of your concepts!!

33. Amazing blog! Do you have any recommendations for aspiring writers? I’m hoping to start my own blog soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m totally overwhelmed .. Any tips? Kudos!

34. Excellent blog! Do you have any hints for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally confused .. Any tips? Kudos!

35. Great blog! Do you have any helpful hints for aspiring writers? I’m planning to start my own website soon but I’m a little lost on everything. Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely confused .. Any recommendations? Thanks!

36. Great blog! Do you have any recommendations for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any tips? Thanks a lot!

37. Hi there, I found your site by means of Google even as looking for a comparable topic, your site got here up, it seems good. I’ve bookmarked it in my google bookmarks.

38. Hello there, I found your blog by way of Google whilst searching for a comparable subject, your web site got here up, it seems to be good. I’ve bookmarked it in my google bookmarks.

39. Hi there, I found your web site by means of Google while searching for a related matter, your website got here up, it seems to be good. I have bookmarked it in my google bookmarks.

40. Great blog! Do you have any tips and hints for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally confused .. Any tips? Kudos!

41. Amazing blog! Do you have any tips and hints for aspiring writers? I’m hoping to start my own website soon but I’m a little lost on everything. Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any recommendations? Thank you!

42. Amazing blog! Do you have any tips and hints for aspiring writers? I’m hoping to start my own website soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely confused .. Any ideas? Bless you!

43. Hi there, I found your blog via Google even as looking for a related subject, your web site came up, it looks great. I’ve bookmarked it in my google bookmarks.

44. Hello there, I found your website by way of Google even as looking for a related matter, your site came up, it appears good. I’ve bookmarked it in my google bookmarks.

45. Hi there, I discovered your web site via Google at the same time as searching for a similar topic, your web site got here up, it seems to be great. I have bookmarked it in my google bookmarks.

46. Great blog! Do you have any tips and hints for aspiring writers? I’m hoping to start my own blog soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any suggestions? Kudos!

47. Amazing blog! Do you have any helpful hints for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m totally overwhelmed .. Any tips? Thanks!

48. Jordan 12 Gym Red 2018 http://www.jordan12gymred.us.com/
Nike Outlet satore http://www.nikefactoryoutletstoreonline.com/
Nike Outlet satore http://www.nikefactoryoutletstoreonline.us/
Nike Outlet satore http://www.nikestores.us.com/
retro jordan 33 http://www.jordan33.us/
cheap jerseys http://www.cheapjerseysfromchina.us/
nfl jerseys http://www.customnfljerseys.us/
air jordan 11 concord http://www.jordan11concord.us.com/
Jordan 12 Gym Red 2018 http://www.jordan12gymred.us/
Jordan 12 Gym Red 2018 http://www.redjordan12.us/
Yeezys http://www.yeezy.com.co/
Yeezy Shoes http://www.yeezys.us.com/
Yeezy Shoes http://www.yeezysupply.us.com/
Yeezy Boost 350 http://www.yeezy-shoes.us.com/
Yeezy Boost http://www.yeezy-boost350.com/
Yeezy Boost http://www.yeezyboost350.us.com/
Yeezy Blue Tint http://www.yeezybluetint.com/
Yeezy 500 http://www.yeezy500utilityblack.com/
Yeezy 500 http://www.yeezy500utilityblack.us/
Nike VaporMax http://www.vapor-max.org.uk/
Salomon Shoes http://www.salomon-shoes.org.uk/
Salomon UK http://www.salomons.me.uk/
Salomon Shoes http://www.salomonspeedcross4.org.uk/
Off White Air Jordan 1 http://www.offwhitejordan1.com/
Nike VaporMax http://www.nikevapormax.org.uk/
Nike Element 87 http://www.nikereactelement87.us.com/
React Element 87 http://www.nikereactelement87.us/
Nike Vapormax Plus http://www.nikeplus.us/
Nike Outlet http://www.nike–outlet.us/
Nike Outlet Store http://www.nikeoutletstoreonlineshopping.us/
Nike Outlet Store http://www.nikeoutletonlineshopping.us/
Cheap Nike NBA Jerseys http://www.nikenbajerseys.us/
Nike Air Max http://www.nikeairmax.us/
Nike Air Max 2017 http://www.max2017.us/
Jordan Shoes 2018 http://www.jordan-com.com/
Jordan 11 Concord 2018 http://www.jordan11-concord.com/
Cheap Yeezy Boost http://www.cs7boots1.com/
Wholesale Cheap NBA Jerseys http://www.cheapnba-jerseys.us/
Birkenstock Sandals http://www.birkenstocksandalsuk.me.uk/
Balenciaga http://www.balenciaga.me.uk/
Balenciaga UK http://www.balenciagauk.org.uk/
Balenciaga http://www.balenciagatriples.org.uk/
Balenciaga UK http://www.birkenstocks.me.uk/
Balenciaga http://www.balenciagatrainers.org.uk/
Nike Air Max 270 http://www.airmax270.org.uk/

49. A person essentially assist to make critically articles I would state. This is the first time I frequented your web page and to this point? I surprised with the research you made to create this actual publish incredible. Wonderful job!

50. A person essentially lend a hand to make seriously articles I might state. This is the very first time I frequented your web page and so far? I amazed with the research you made to make this particular post incredible. Magnificent process!

51. I don’t even know the way I finished up here, but I assumed this post used to be great. I do not understand who you might be however definitely you are going to a famous blogger should you aren’t already. Cheers!

52. A person necessarily lend a hand to make severely posts I would state. This is the first time I frequented your web page and thus far? I amazed with the research you made to create this actual post incredible. Fantastic task!

53. Having read this I thought it was extremely enlightening. I appreciate you spending some time and effort to put this article together. I once again find myself spending way too much time both reading and posting comments. But so what, it was still worth it!

54. you’re really a good webmaster. The site loading velocity is amazing. It sort of feels that you’re doing any unique trick. Moreover, The contents are masterwork. you have done a fantastic job in this matter!

55. Pretty portion of content. I just stumbled upon your site and in accession capital to say that I get actually loved account your weblog posts. Any way I will be subscribing in your feeds and even I fulfillment you access constantly fast.

56. Attractive section of content. I just stumbled upon your website and in accession capital to claim that I get actually enjoyed account your weblog posts. Anyway I will be subscribing in your augment or even I success you access constantly rapidly.

57. you are really a good webmaster. The site loading speed is incredible. It sort of feels that you’re doing any distinctive trick. Moreover, The contents are masterwork. you’ve performed a great process on this matter!

58. Attractive section of content. I simply stumbled upon your web site and in accession capital to assert that I get actually enjoyed account your blog posts. Anyway I’ll be subscribing in your feeds or even I fulfillment you access constantly fast.