[leetcode]309. Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:如何用c语言编写程序 编辑:程序博客网 时间:2024/06/11 20:39

题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

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

Example:

prices = [1, 2, 3, 0, 2]maxProfit = 3transactions = [buy, sell, cooldown, buy, sell]

解题思路:设买入状态为buyUp,卖出状态为sellUp,

                  买入状态分两种情况:一、和前一天的状态一样;二、前两天是卖出,前一天是冷却期,今天买入。

                  卖出状态分两种情况:一、和前一天的状态一样;二、前一天是买入状态,今天卖出。

                  状态转移方程:buyUp[i]=max(buyUp[i-1],sellUp[i-2]-prices[i])

                                           sellUp[i]=max(sellUp[i-1],buyUp[i-1]+prices[i])

                  最后一天肯定是卖出。


class Solution{public:    int maxProfit(vector<int>& prices)//profit=max()    {        if (prices.size()==0)            return 0;        vector<int> sellUp(prices.size(),0);        vector<int> buyUp(prices.size(),0);        buyUp[0]=-prices[0];        sellUp[0]=0;        for(int i=1;i<prices.size();i++)        {            if(i<2)                buyUp[i]=max(buyUp[i-1],-prices[i]);            else                buyUp[i]=max(buyUp[i-1],sellUp[i-2]-prices[i]);            sellUp[i]=max(sellUp[i-1],buyUp[i-1]+prices[i]);        }        return sellUp[prices.size()-1];    }};


0 0