您的位置:首页 > 其它

股票最大收益问题3 Best Time to Buy and Sell Stock III

2014-02-28 21:49 363 查看
问题: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.
题目源自于Leetcode。
给出一个数组,这一次,要求的是,最多可以发生股票买卖两次,并且两次时间不可以重叠。要求收益最大。

思路一:说是最多2次。举例子试试会发现,除非没办法买卖2次,否则买卖2次绝对比买卖1次收益更大。先考虑最大收益的一次买卖(这个问题是之前的问题http://blog.csdn.net/ojshilu/article/details/16845985)。找到收益最大的一次买卖之后,存在可能的三种情况:

1、最大的这次买卖的中间也有不小的起伏,如果在其中间穿插一次买卖,形成2次买卖,总收益最大。

2、最大的这次买卖的左侧存在一个较大的买卖。

2、最大的这次买卖的右侧存在一个较大的买卖。

这三种情况只有都求出来比较一下谁更大,才能得到结果。

该方法时间复杂度O(N),空间复杂度O(1)。

class Solution {
public:

int getmax(vector<int> &prices, int from, int to, int &lowest, int &highest)
{
lowest = highest = from;
int maxmum = 0;
int low = from;
for(int i=from; i<to ;i++)
{
if(prices[i] < prices[low])
low = i;
if(prices[i] - prices[low] > maxmum)
{
maxmum = prices[i] - prices[low];
highest = i;
lowest = low;
}
}
return maxmum;
}

int getmin(vector<int> &prices, int from, int to, int &lowest , int &highest)
{
lowest = highest = from;
int maxmum = 0;
int high = from;
for(int i=from; i<to ;i++)
{
if(prices[i] > prices[high])
high = i;
if(prices[high] - prices[i] > maxmum)
{
maxmum = prices[high] - prices[i];
lowest = i;
highest = high;
}
}
return maxmum;
}
int max(int a, int b, int c)
{
if(a>b)
return a>c?a:c;
else
return b>c?b:c;
}

int maxProfit(vector<int> &prices) {
int len = int(prices.size());
if(len == 0)
return 0;

int lowest, highest;
int maxmum;
maxmum = getmax(prices, 0, len, lowest, highest);

int left = lowest; //记录最大买卖的左边沿
int right = highest;//记录最大买卖的右边沿

lowest = highest = 0;
int m_left =  getmax(prices, 0, left, lowest, highest);
int m_right = getmax(prices, right+1, len, lowest, highest);
int m_mid = getmin(prices, left+1, right, lowest, highest);

return maxmum + max(m_left, m_right, m_mid);
}

};


思路二:左右夹击。从左向右遍历,记录下每个位置左侧的最大买卖。从右向左遍历,记录下每个位置右侧的最大买卖。这样,对于任意一个位置其左右侧的最大买卖之和都会知道。
该方法时间复杂度O(N),空间复杂度O(N)。

class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if(n < 2)
return 0;
vector<int> left(n, 0); //left[i]记录0~i中的最大买卖
vector<int> right(n, 0); //right[i]记录i~n-1中的最大买卖

for(int i=1, valley = prices[0]; i<n;i++)
{
valley = min(valley, prices[i]);
left[i] = max(left[i-1], prices[i] - valley);
}

for(int i = n-2, peak = prices[n-1];i>=0;i--)
{
peak = max(peak, prices[i]);
right[i] = max(right[i+1], peak - prices[i]);
}
int result = 0;
for(int i=0;i<n;i++)
result = max(result, left[i] + right[i]);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐