码迷,mamicode.com
首页 > 其他好文 > 详细

123. Best Time to Buy and Sell Stock III (Array; DP)

时间:2015-10-14 19:39:46      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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).

思路:把要求的东西profits设成状态。 从左往右,从右往左两次scan赋值状态,然后再扫描一次状态,所以时间复杂度O(n) *3

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.empty()) return 0;
       
        int size = prices.size();
        int maxProfit = 0;  
        int* profits = new int [size]; //表示从0到i的最大利润
        int* profits_from_last = new int [size]; //表示从i到size-1的最大利润
        
        //initial status    
        profits[0] = 0;
        int minValue = prices[0];
  
       //scan from start          
        for(int i = 1; i< size; i++)
        {
            if(prices[i] < minValue)
            {
                minValue = prices[i];
                profits[i] = profits[i-1];
            }
            else
            {
                profits[i] = max(prices[i]-minValue,profits[i-1]);
            }
             
        }
        
        //initial status
        profits_from_last[size-1] = 0;
        int maxValue = prices[size-1];
        
        //scan from last
        for(int i = size-2; i >=0 ; i--)
        {
             if(prices[i] > maxValue)
             {
                 maxValue = prices[i];
                 profits_from_last[i] = profits_from_last[i+1];
             }
             else
             {
                 profits_from_last[i] = max(maxValue-prices[i],profits_from_last[i+1]);
             }
            
             int profit = profits[i] + profits_from_last[i];
             if(profit>maxProfit)
             {
                 maxProfit = profit;
             }
        }
        return maxProfit;      
    }
};

 

123. Best Time to Buy and Sell Stock III (Array; DP)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4878356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!