您的位置:首页 > 其它

leetcode || 123、Best Time to Buy and Sell Stock III

2015-04-27 10:28 676 查看
problem:

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).

Hide Tags
Array Dynamic
Programming

题意:给定一支股票的价格表,最多有两手交易,求最大利润。很经典的一道算法题!

thinking:

(1)读懂最多有两首交易:其实就是说第一次卖和第二次买有可能在同一天

(2)开两个数组,一个用于顺序记录到该天为止的最大收益,另一个记录该天后面的最大收益。

首先,因为能买2次(第一次的卖可以和第二次的买在同一时间),但第二次的买不能在第一次的卖左边。

所以维护2个表,f1和f2,size都和prices一样大。

意义:

f1[i]表示 -- 截止到i下标为止,左边所做交易能够达到最大profit;

f2[i]表示 -- 截止到i下标为止,右边所做交易能够达到最大profit;

那么,对于f1 + f2,寻求最大即可。

code:

class Solution {
public:
int maxProfit(vector<int> &prices) {
int size = prices.size();
if (size == 0)
return 0;

vector<int> f1(size);
vector<int> f2(size);

int minV = prices[0];
for (int i = 1; i < size; i++){
minV = std::min(minV, prices[i]);
f1[i] = std::max(f1[i-1], prices[i] - minV);
}

int maxV = prices[size-1];
f2[size-1] = 0;
for (int i = size-2; i >= 0; i--){
maxV = std::max(maxV, prices[i]);
f2[i] = std::max(f2[i+1], maxV - prices[i]);
}

int sum = 0;
for (int i = 0; i < size; i++)
sum = std::max(sum, f1[i] + f2[i]);

return sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: