首页 > 代码库 > Leetcode--Best Time to Buy and Sell Stock III

Leetcode--Best Time to Buy and Sell Stock III

Problem Description:

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

分析:

按照题意,要求根据每天的股票价格,交易两次得到最大的利润。直接的想法就是利用分治法,从前往后循环依次将数组分为前后两个股票价格序列,分别得到最大的利润,将两者相加得到两次交易的最大利润,时间复杂度O(n^2),提交果然超时了。

代码如下:

class Solution {
public:

    int profit(vector<int> &vec,int beg,int last)
    {
        int res=0;
        if(beg==last)
            return res;
        int min=vec[beg];
        for(int i=beg+1;i<=last;++i)
        {
            if(vec[i]>min)
            {
                int temp=vec[i]-min;
                if(temp>res)
                    res=temp;
            }
            else
                min=vec[i];
        }
        return res;
    }

    int maxProfit(vector<int> &prices) {
        int res=0;
        int n=prices.size();
        if(n<=1)
            return res;

        for(int i=1;i<n-1;i++)
        {
            int res1=profit(prices,0,i);
            int res2=profit(prices,i+1,n-1);
            if((res1+res2)>res)
                res=res1+res2;
        }

        return res;
    }
};

看了discus以后发现其实可以在O(n)时间内将前后两部分的最大利润求出来,具体实现就是用两个数组分别存储从前往后和从后往前两次遍历时每天的最大利润,最后得到两次交易能够获得的最大利润。

具体代码如下:

class Solution {
public:

    int maxProfit(vector<int> &prices) {
        int res=0;
        int n=prices.size();
        if(n<=1)
            return res;
        vector<int> front(n,0);
        vector<int> back(n,0);
        int minp=prices[0];
        int maxp=prices[n-1];
        for(int i=1;i<n;i++)
        {
            if(prices[i]>minp)
                front[i]=prices[i]-minp;
            else
                minp=prices[i];
        }
        for(int i=n-2;i>=0;i--)
        {
            if(prices[i]>maxp)
                maxp=prices[i];
                
            back[i]=max(maxp-prices[i],back[i+1]);
            if(front[i]+back[i]>res)
                res=front[i]+back[i];
                
        }

        return res;
    }
};