题目:买股票的最佳时间含冷冻期
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 = 3 transactions = [buy, sell, cooldown, buy, sell]
题意:
给定一个数组,第i个元素代表某只股票在第i天的价格。设计一个算法计算最大收益。你可以完成多次交易(亦即,多次买入、卖出同一只股票),需要满足下列限制:
限制:
1、你不可以在同一时间参与多个交易(亦即,在买入股票之前必须卖出)。
2、在卖出股票之后,你不可以在第二天马上买入。(亦即,需要一天的冷却(CD)时间)。
转载地址:http://bookshadow.com/weblog/2015/11/24/leetcode-best-time-to-buy-and-sell-stock-with-cooldown/#0-tsina-1-7114-397232819ff9a47a7b7e80a40613cfe1
思路一:动态规划。
引入辅助数组sells
和buys
第i天交易时获得的累计收益只与第i-1天与第i-2天有关
记第i天与第i-1天的价格差:delta = price[i] - price[i - 1]
状态转移方程为:
上述方程的含义为:
而实际上:
所求的最大收益为max(sells)
。显然,卖出股票时才可能获得收益。
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if (n == 0) return 0; vector<int> buys(n); vector<int> sells(n); sells[0] = 0, buys[0] = -prices[0]; for (int i=1; i<n; i++) { int delta = prices[i] - prices[i-1]; sells[i] = max(buys[i-1] + prices[i], sells[i-1] + delta); buys[i] = max(buys[i-1] - delta, sells[i-2] - prices[i]); } int profit = 0; for (int x : sells) { if (x > profit) profit = x; } return profit; } };
思路二:
引入辅助数组sells
和buys
状态转移方程:
所求最大收益为sells[n-1]
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if (n < 2) return 0; vector<int> buys(n); vector<int> sells(n); sells[0] = 0, sells[1] = max(0, prices[1] - prices[0]); buys[0] = -prices[0], buys[1] = max(-prices[0], -prices[1]); for (int i=2; i<n; i++) { sells[i] = max(sells[i-1], buys[i-1] + prices[i]); buys[i] = max(buys[i-1], sells[i-2] - prices[i]); } return sells[n-1]; } };
算法空间复杂度为O(1)的版本:C++版:8ms
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if (n < 2) return 0; int currBuy = -prices[0]; int currSell = 0; int prevSell = 0; for (int i=1; i<n; i++) { int temp = currSell; currSell = max(currSell, currBuy + prices[i]); if (i >= 2) { currBuy = max(currBuy, prevSell - prices[i]); } else { currBuy = max(currBuy, -prices[i]); } prevSell = temp; } return currSell; } };