LeetCode_Best Time to Buy and Sell Stock III

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;

    }

};

分析: 这道题主要是求一个分界点,分界点左侧的最大收益和右侧的最大收益之和最大,当然也可能只进行了一次交易。所以上面两边遍历,第一遍遍历求得是分界点左侧的最大收益,第二遍求得是分界点右侧的最大收益。

你可能感兴趣的:(LeetCode)