122. Best time to Buy and Sell Stock II

Source: Internet
Author: User

1.

ref:http://blog.csdn.net/linhuanmars/article/details/23164149

The difference is that it can be traded infinitely many times (of course we know that the deal will not exceed n-1 times, that is, every day we sell first and buy it). Since there is no limit to the number of transactions, we can see that we can get the maximum profit if we trade for a two-day spread greater than 0. So the algorithm is actually adding up all the spreads greater than 0 can be, very simple. So only a single scan is required, the time complexity is O (n), space only need O (1) to save a cumulative result can be.

1      Public intMaxprofit (int[] prices) {2         if(Prices.length < 1) {3             return0;4         }5         intdiff = 0;6          for(inti = 1; i < prices.length; i++) {7diff + = (prices[i]-prices[i-1] > 0)? Prices[i]-prices[i-1]: 0;8         }9         returndiff;Ten}

2. Motion Regulation

Maintain two variables:

1. End of day, no stock on hand

1) No stock in the past, nothing to do today

2) There were stocks, bought today

2. The end of the day, there is stock in hand

1) No previous stock, buy today

2) There were stocks, and nothing was done today.

1      Public intMaxprofit (int[] prices) {2         if(Prices.length < 1) {3             return0;4         }5         intNostock = 0;6         intHavestock = 0-prices[0];7          for(inti = 1; i < prices.length; i++) {8             intOldnostock =Nostock;9Nostock = Math.max (nostock, Havestock +prices[i]);TenHavestock = Math.max (Havestock, Nostock-prices[i]); One         } A         returnNostock; -}

122. Best time to Buy and Sell Stock II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.