309. Best time to Buy and Sell Stock with Cooldown

Source: Internet
Author: User

    /** 309. best time to Buy and Sell Stock with Cooldown * 2016-7-4 by Mingyang *http://buttercola.blogspot.com/2016/01/leetcode-best-time-to-buy-and-sell.html     * * * *. Define states * *to represent the decision at index I: *buy[i]: Max profit till index I.     The series of transaction is ending with a buy. *SELL[I]: Max profit till index I.     The series of transaction is ending with a sell.     *to clarify: *till index I, the Buy/sell action must happen and must is the last action. * It may not be happen at index I. It may happen at I-1, I-2, ... 0. *in the end n-1, return sell[n-1].      Apparently we cannot finally end up with a buy.     *in, we would rather take a rest at n-1.      *for Special Case No transaction @ all, classify it as sell[i], so, the the end, we can still return sell[n-1]. * * *. Define recursion * *buy[i]: To make a decision whether to buy on I, we either take a rest, by just using the old D Ecision at I-1, *or sell At/before i-2, then buy at I, We cannot sell at I-1, then buy at I, because of Cooldow N. *sell[i]: To make a decision whetherTo sell in I, we either take a rest, by just using the old decision at I-1, *or buy At/before i-1, then sell at I     .        *so we get the following formula: *buy[i] = Math.max (Buy[i-1], sell[i-2]-prices[i]);      *sell[i] = Math.max (Sell[i-1], buy[i-1] + prices[i]);*/      Public intMAXPROFIT5 (int[] prices) {            if(Prices = =NULL|| Prices.length <= 1) {                return0; }            int[] Sell=New int[Prices.length]; int[] buy=New int[Prices.length]; buy[0] =-prices[0]; sell[0] = 0; buy[1]=math.max (buy[0],-prices[1]); sell[1]=math.max (sell[0],buy[0]+prices[1]);  for(inti = 2; I <prices.length; i++) {Buy[i]=math.max (buy[i-1],sell[i-2]-Prices[i]); Sell[i]=math.max (sell[i-1],buy[i-1]+Prices[i]); }            returnSell[prices.length-1]; }

309. Best time to Buy and Sell Stock with Cooldown

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.