Leetcode best time to Buy and Sell Stock with Cooldown

Source: Internet
Author: User

The original title link is here: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

Topic:

Say you has an array for which the i-th element is the price of a given-stock on day I.

Design an algorithm to find the maximum profit. Many transactions as (ie, buy one and sell one share of the stock multiple times) with the FO Llowing Restrictions:

    • Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
    • After you sell your the stock, you cannot buy the stock on next day. (ie, cooldown 1 day)

Example:

Prices = [1, 2, 3, 0, 2]maxprofit = 3transactions = [Buy, Sell, cooldown, buy, sell]

Exercises

Similar to the best time to Buy and Sell stock.

There are three states S0, S1, S2. S0 buy stock becomes s1, S1 sell stock becomes s2.

s0[I] =Maxs0[I1],s2[I1]);//StayAtS0,OrRestFromS2s1[I] =Maxs1[I1], s0[i-1]-prices[i]); //stay at S1, or buy from s0s2[i] = s1[i-1] + prices[i]; //only one way from s1           

Time Complexity:o (n). Space:o (n).

AC Java:

1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         if(Prices = =NULL|| Prices.length = = 0){4             return0;5         }6         intLen =prices.length;7         int[] S0 =New int[Len];8         int[] S1 =New int[Len];9         int[] s2 =New int[Len];Ten          OneS0[0] = 0; AS1[0] =-prices[0]; -S2[0] = 0; -          for(inti = 1; i<len; i++){ theS0[i] = Math.max (s0[i-1],s2[i-1]); -S1[i] = Math.max (s1[i-1], s0[i-1]-prices[i]); -S2[i] = s1[i-1] +Prices[i]; -         } +         returnMath.max (s0[len-1], s2[len-1]); -     } +}

Reference:https://leetcode.com/discuss/72030/share-my-dp-solution-by-state-machine-thinking

Leetcode 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.