Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:手机淘宝标题优化技巧 编辑:程序博客网 时间:2024/05/17 07:50

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]
解析:

这题的状态好烦啊,开始不想用状态,想了很多种情况,头昏脑涨的,后来看了大神的解答,代码很简单,状态总结为buy[i],sell[i]分别表示到i之前的最后一个操作分别是买和卖,状态转移方程如下:

buy[i] = max(sell[i-2]-price, buy[i-1])sell[i] = max(buy[i-1]+price, sell[i-1])
虽然分析起来可以理解,但是自己想还是挺难的。

代码:

class Solution {public:    int maxProfit(vector<int>& prices) {              if (prices.empty()) return 0;        if (prices.size()==1) return 0;        if (prices.size()==2) return max(0,prices[1]-prices[0]);        int buy=0;        int buy1=0;        int buy2=0;        int sell1=0;        int sell=0;        int sell2=0;                buy2=-prices[0];        buy1=-min(prices[0],prices[1]);        sell2=0;        sell1=max(0,prices[1]-prices[0]);                for (int i=2; i<prices.size(); i++)        {            buy=max(sell2-prices[i],buy1);            sell=max(buy1+prices[i],sell1);                        buy1=buy;            sell2=sell1;            sell1=sell;           // buy2=buy1;                   }        return sell;    }};



0 0
原创粉丝点击