问题:Best Time to Buy and Sell Stock III
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 at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
这是上一周的加强版,与之前不同的是限制了交易的次数,故不能使用贪心算法。如果每次有赚差价的机会都进行交易,会浪费掉交易机会而取不到最佳。所以我们需要用一个2*4的数组来存储他们的收益状态,其中两行分别是当前和接下来的收益状态。四列分别是第一次买入,第一次卖出,第二次买入,第二次卖出的状态。每次交易后,所得的收益与之前的收益以及当天股票价格有关,具体的关系也比较简单,比如第一次卖出的收益等于当前第一次买入的收益加上当天的价格,别的收益也是如此计算。最后取第一次卖出与第二次卖出的收益较大者即使最大收益。
代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int states[2][4] = {INT_MIN, 0, INT_MIN, 0}; // 0: 1 buy, 1: one buy/sell, 2: 2 buys/1 sell, 3, 2 buys/sells
int len = prices.size(), i, cur = 0, next =1;
for(i=0; i<len; ++i)
{
states[next][0] = max(states[cur][0], -prices[i]);
states[next][1] = max(states[cur][1], states[cur][0]+prices[i]);
states[next][2] = max(states[cur][2], states[cur][1]-prices[i]);
states[next][3] = max(states[cur][3], states[cur][2]+prices[i]);
swap(next, cur);
}
return max(states[cur][1], states[cur][3]);
}
};
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 at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
这是上一周的加强版,与之前不同的是限制了交易的次数,故不能使用贪心算法。如果每次有赚差价的机会都进行交易,会浪费掉交易机会而取不到最佳。所以我们需要用一个2*4的数组来存储他们的收益状态,其中两行分别是当前和接下来的收益状态。四列分别是第一次买入,第一次卖出,第二次买入,第二次卖出的状态。每次交易后,所得的收益与之前的收益以及当天股票价格有关,具体的关系也比较简单,比如第一次卖出的收益等于当前第一次买入的收益加上当天的价格,别的收益也是如此计算。最后取第一次卖出与第二次卖出的收益较大者即使最大收益。
代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int states[2][4] = {INT_MIN, 0, INT_MIN, 0}; // 0: 1 buy, 1: one buy/sell, 2: 2 buys/1 sell, 3, 2 buys/sells
int len = prices.size(), i, cur = 0, next =1;
for(i=0; i<len; ++i)
{
states[next][0] = max(states[cur][0], -prices[i]);
states[next][1] = max(states[cur][1], states[cur][0]+prices[i]);
states[next][2] = max(states[cur][2], states[cur][1]-prices[i]);
states[next][3] = max(states[cur][3], states[cur][2]+prices[i]);
swap(next, cur);
}
return max(states[cur][1], states[cur][3]);
}
};