您的位置:首页 > 其它

Leetcode74: Best Time to Buy and Sell Stock III

2015-09-22 14:40 447 查看
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).
只能允许两次买卖,可以用动态规划的思想,第一步扫描,先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。第二步是逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。 所以最后算法的复杂度就是O(n)的。

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

int *cost1 = new int[size];
cost1[0] = 0;
int min = prices[0];
int res = 0;
for(int i = 1; i < size; i++)
{
if(prices[i] < min)
min = prices[i];
if(prices[i] - min > res)
res = prices[i] - min;
cost1[i] = res;
}

int *cost2 = new int[size];
cost2[size-1] = 0;
int max = prices[size-1];
res = 0;
for(int i = size-2; i >= 0; i--)
{
if(prices[i] > max)
max = prices[i];
if(max - prices[i] > res)
res = max - prices[i];
cost2[i] = res;
}

int result = cost1[0]+cost2[0];
for(int i = 0; i < size; i++)
{
if(cost1[i]+cost2[i] > result)
result = cost1[i]+cost2[i];
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: