Leetcode 309. Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:php的框架有哪些 编辑:程序博客网 时间:2024/06/05 06:24
题目:

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)
思路:1,自己刚开始想的是:整个数组分为两种情况:交易两次及两次以上的(会出现colddown);交易一次的(也就是数组中前后最大差值);所以问题为两个中的最大值,第一种情况分别假设第i天为colddown,则colddown前后两个数组也原问题一样,取最大值时候的第i天结果,递归下去就行。209 / 211 test cases passed.。GG
class Solution {public:int bestprice(int left,int right ,vector<int>& a){int min=0,max=0,diffenerce=0;for(int i=left;i<right;i++){min=a[i];for(int j=i+1;j<=right;j++){max=a[j];if((max-min)>diffenerce)diffenerce=max-min;}}if((right-left)<=0){return 0;}else{if(right-left==1){return (a[right]-a[left])<0?0:(a[right]-a[left]);}else{   int temp=0;  for(int i=left+2;i<right-1;i++)      {      temp= bestprice(left,i-1,a)+bestprice(i+1,right,a)<temp?temp:bestprice(left,i-1,a)+bestprice(i+1,right,a);      }  return temp<diffenerce?diffenerce:temp;}}}    int maxProfit(vector<int>& prices) {        int i=0,j=prices.size();        return bestprice(0,j-1,prices);    }};
2,参考网上大神,吊打:原地址

http://bookshadow.com/weblog/2015/11/24/leetcode-best-time-to-buy-and-sell-stock-with-cooldown/

sells[i]表示在第i天卖出股票所能获得的最大累积收益buys[i]表示在第i天买入股票所能获得的最大累积收益初始化令sells[0] = 0,buys[0] = -prices[0]
sells[i] = max(buys[i - 1] + prices[i], sells[i - 1] + delta) buys[i] = max(sells[i - 2] - prices[i], buys[i - 1] - delta)

上述方程的含义为:

第i天卖出的最大累积收益 = max(第i-1天买入~第i天卖出的最大累积收益, 第i-1天卖出后反悔~改为第i天卖出的最大累积收益)第i天买入的最大累积收益 = max(第i-2天卖出~第i天买入的最大累积收益, 第i-1天买入后反悔~改为第i天买入的最大累积收益)

而实际上:

第i-1天卖出后反悔,改为第i天卖出 等价于 第i-1天持有股票,第i天再卖出第i-1天买入后反悔,改为第i天买入 等价于 第i-1天没有股票,第i天再买入
class Solution {public:    int maxProfit(vector<int>& prices) {        int buy = INT_MIN, pre_buy = 0, sell = 0, pre_sell = 0;        for (int price : prices) {            pre_buy = buy;            buy = max(pre_sell - price, pre_buy);            pre_sell = sell;            sell = max(pre_buy + price, pre_sell);        }        return sell;    }};


阅读全文
0 0
原创粉丝点击