Say you have an array for which the i thelement is the price of a given stock on dayi.
Design an algorithm to find the maximum profit. You may complete at most twotransactions.
Note: 
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题意:股票最多能卖两次,求最大收益;
思路:动态规划,以第i天为分界线,计算第i天之前进行一次交易的最大收益pre[i],和第i天之后进行一次交易最大收益postProfit[i]
最后遍历一遍max(pre[i]+post[i])最大值
class Solution
{
	int maxProfit(vector<int> &prices)
	{
		if (prices.size()<=1)
		{
			return 0;
		}
		int n = prices.size();
		int * preProfit = new int[n]();
		int * postProfit = new int[n]();
		int curMin = prices[0];
		for (int i=1; i<n; i++)
		{
			curMin = min(curMin, prices[i]);
			preProfit[i] = max(preProfit[i-1], prices[i]-curMin);
		}
		int curMax = prices[n-1];
		for (int i=n-2; i>=0; i--)
		{
			curMax = max(curMax, prices[i]);
			postProfit[i] = max(postProfit[i + 1], curMax - prices[i]);
		}
		int maxProfit = 0;
		for (int i = 0; i<n; i++)
		{
			maxProfit = max(maxProfit, postProfit[i] + preProfit[i]);
		}
		delete[] postProfit;
		delete[] preProfit;
		return maxProfit;
	}
}; 
                   
                   
                   
                   
                             本文介绍了一种通过动态规划解决股票交易最大收益问题的方法,允许进行最多两次买卖操作,并确保每次卖出后才能再次购买。
本文介绍了一种通过动态规划解决股票交易最大收益问题的方法,允许进行最多两次买卖操作,并确保每次卖出后才能再次购买。
           
       
           
                 
                 
                 
                 
                 
                
               
                 
                 
                 
                 
                
               
                 
                 扫一扫
扫一扫
                     
              
             
                   345
					345
					
 被折叠的  条评论
		 为什么被折叠?
被折叠的  条评论
		 为什么被折叠?
		 
		  到【灌水乐园】发言
到【灌水乐园】发言                                
		 
		 
    
   
    
   
             
            


 
            