Best Time to Buy and Sell Stock III

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

思路:最佳时间买入卖出股票,但是这题与前两题有所不同而且比较难,最多进行两次买卖,但是同一时间手上只能保持一个股票。使用动态规划思想,是比较好的思路(PS:也是借鉴网上大神思路).先正序扫描0~i天的最大利润,在倒序扫描i+1~n天的最大利润,放在两个数组中,然后求出第i项最大和。

1.min1=prices[0];

2.定义profit1数组,保存正序扫描的利润:profit1[i]=profit1[i]-min(prices[i],min1)当profit1[i]-min(prices[i],min1)>profit1[i-1];反之则为profit1[i]=proft1[i-1];

3.max1=prices[n-1]

4.定义profit2数组,保存逆序扫描的最大利润:profit2[i]=max(prices[i],max1)-prices[i],当max(prices[i],max1)-prices[i]>profit2[i+1];反之,profit2[i]=profit2[i+1];

5.最后把第i项最大和求出,返回最大利润。

class Solution {

public:

    int maxProfit(vector<int> &prices) {

        int n=prices.size();

        if(n<=0)

            return 0;

        vector<int> profit1(n,0);

        vector<int> profit2(n,0);

        int min=prices[0];

        for(int i=1;i<n-1;i++)

        {

            if(prices[i]<min)

                min=prices[i];

            if(prices[i]-min>profit1[i-1])

                profit1[i]=prices[i]-min;

            else

                profit1[i]=profit1[i-1];

        }

        int max=prices[n-1];

        for(int i=n-2;i>=0;i--)

        {

            if(prices[i]>max)

                max=prices[i];

            if(max-prices[i]>profit2[i+1])

                profit2[i]=max-prices[i];

            else

                profit2[i]=profit2[i+1];

        }

        int maxprofits=0;

        for(int i=0;i<n-1;i++)

        {

            if(profit1[i]+profit2[i]>maxprofits)

                maxprofits=profit1[i]+profit2[i];

        }

        return maxprofits;

    }

};

 

你可能感兴趣的:(time)