Leetcode::Best Time to Buy and Sell Stock III

最多两次交易,如果分成两个时间段的话,即把数组分成两段。分别求出两段的最大利润,最后相加,从而得到最大利润。

那怎么分两段呢?假设t来表示所分的分点,t= 1,2,....n-1 (n是数组长度)。用一维数组来记录 i=0 到 t 段 中的 最大利润值。

上边求出来的只是第一段的最大利润值,为了求出第二段的最大利润值,逆向遍历数组。与第一段的方法相同求出第二段的最大利润值。

最后求出,第一段最大利润值和第二段最大利润值和中的最大值就是我们要求出的最大利润值。

class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.size() ==0|| prices.size() == 1)
{
return 0;
}
int min= prices[0];
int max = 0;
vector<int> tmp;
tmp.push_back(0);

for( int i = 1; i < prices.size(); ++i )
{
if( prices[i] < min )
{
min=prices[i];
}

if( prices[i] - min > max)
{
max=prices[i]-min;
}

tmp.push_back(max);
}

int re_max =0;
int l_max = 0;
int last=prices[prices.size()-1];

for( int j = tmp.size()-1; j >= 0; --j )
{
if( prices[j] > last )
{
last=prices[j];
}

if( last - prices[j] > l_max )
{
l_max = last - prices[j];
}

if( l_max + tmp[j] > re_max )
{
re_max =l_max + tmp[j];
}
}

return re_max;
}
};

posted @ 2013-05-29 20:56  NinaGood  阅读(274)  评论(0编辑  收藏  举报