您的位置:首页 > 其它

LeetCode_Best Time to Buy and Sell Stock III

2013-04-11 23:31 393 查看
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.size() <2) return 0;
int *profit = new int[prices.size()];
memset(profit,0, sizeof(int)*prices.size()) ;
int i,min,maxProfit = 0,maxValue;
min = prices[0] ;
for(i =1; i< prices.size();i++)
{
if(prices[i] >= min )
{
maxProfit = max(maxProfit,prices[i]- min ) ;
profit[i] = maxProfit ;
}else
{
profit[i] = maxProfit ;
min = prices[i];
}
}
i--;
maxValue= prices[i] ;
maxProfit = 0;
for( i--; i>= 0;i--)
{
if(prices[i] < maxValue )
{
maxProfit = max(maxProfit,maxValue - prices[i] );
profit[i] += maxProfit ;
}else
{
profit[i] += maxProfit ;
maxValue =  prices[i];
}
}
maxProfit = profit[0];
for(i=1;i<prices.size();i++)
if(profit[i] > maxProfit)
maxProfit = profit[i] ;

delete []profit ;
return maxProfit;
}
};


分析: 这道题主要是求一个分界点,分界点左侧的最大收益和右侧的最大收益之和最大,当然也可能只进行了一次交易。所以上面两边遍历,第一遍遍历求得是分界点左侧的最大收益,第二遍求得是分界点右侧的最大收益。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: