123. Best Time to Buy and Sell Stock III

来源:互联网 发布:淘宝客自动转换工具 编辑:程序博客网 时间:2024/06/10 03:45

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

这题允许股票卖两次
第一种方法暴力求解,对于每个i,我们求[0,i]与[i,n-1]两次收益,然后求和,遍历i,可以取其中的最大值,需要O(N^2)的时间。这样做时间超时了。

class Solution {public:    int maxProfit(vector<int>& prices)     {        int n=prices.size();        if(n<2)            return 0;        int maxprofit=0;        for(int i=0;i<n;i++)        {            int profit1=helper(prices,0,i);            int profit2=helper(prices,i+1,n-1);            if(maxprofit<(profit1+profit2))                maxprofit=profit1+profit2;        }        return maxprofit;    }    int helper(vector<int>& prices,int start,int end)     {        int n=end-start+1;        if(n<2)            return 0;        int CurMin=prices[start];        int profit=0;        for(int i=start;i<=end;i++)        {            CurMin=CurMin<=prices[i]?CurMin:prices[i];            profit=profit>=(prices[i]-CurMin)?profit:(prices[i]-CurMin);        }        return profit;    }};

第二种方法是动态规划:用两个数组,第一个数组f1[i]用来表示在[0,i]内进行买入卖出的最大收益,用f2[i]表示在[i,n-1]内进行买入卖出的最大收益,然后最大收益即为max(f1[i]+f2[i])。

class Solution {public:    int maxProfit(vector<int>& prices)     {        int n=prices.size();        if(n<2)            return 0;        vector<int>profit1(n,0);        vector<int>profit2(n,0);        int minprice=prices[0];        for(int i=1;i<n;i++)        {            minprice=min(minprice,prices[i]);            profit1[i]=max(profit1[i-1],prices[i]-minprice);        }        int maxprice=prices[n-1];        for(int i=n-2;i>=0;i--)        {            maxprice=max(prices[i],maxprice);            profit2[i]=max(profit2[i+1],maxprice-prices[i]);        }        int maxprofit=0;        for(int i=0;i<n;i++)            maxprofit=max(maxprofit,profit1[i]+profit2[i]);        return maxprofit;    }};
0 0
原创粉丝点击