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).
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(!prices.size())return 0;
int *maxl = new int[prices.size() + 1];
int *maxr = new int[prices.size() + 1];
maxl[0] = maxr[prices.size() - 1] = 0;
int mini = prices[0];int m = 0;
for(int i = 1; i < prices.size(); i++)
{
m = max(m,prices[i] - mini);
maxl[i] = m;
mini = min(mini, prices[i]);
}
int maxm = prices[prices.size() - 1];m = 0;
for(int i = prices.size() - 2; i >= 0; i--)
{
m = (m, maxm > prices[i] ? maxm - prices[i] : 0);
maxr[i] = m;
maxm = max(maxm, prices[i]);
}
int rst = maxr[0];
for(int i = 0; i < prices.size() - 1; i++)
{
rst = max(rst, maxl[i] + maxr[i + 1]);
}
return rst;
}
};

本文介绍了一种算法,用于计算给定股票价格序列中通过至多两次买卖交易所能获得的最大利润。该算法采用动态规划思想,分别从前向后和从后向前计算潜在的最大收益,并最终确定最优策略。
534

被折叠的 条评论
为什么被折叠?



