Best Time to Buy and Sell Stock III

来源:互联网 发布:股票预测软件破解 编辑:程序博客网 时间:2024/06/04 23:27

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

这里很容易就想到 用数组 l[i] r[i]分别表示0~i,i+1~n中最大的profit。然后分别计算数组l、r,这样的算法复杂度是O(n^2)

然而有O(N)的算法。

在我们计算l[i+1]的时候,跟l[i]是有关系的。0~i+1最大的利润等于即0~i最大的利润、prices[i+1]-min中的较大者。同样可以求解r[i]

class Solution {public:    int maxProfit(vector<int> &prices) {        int n = prices.size();        if(n==0) return 0;                int l[n];        int r[n];        memset(l,0,sizeof(int)*n);        memset(r,0,sizeof(int)*n);        int min1 = prices[0];        for(int i = 1 ;i<n;i++)        {            l[i] = prices[i]-min1 > l[i-1]?prices[i]-min1:l[i-1];            min1 = min(min1,prices[i]);        }        int max1 = prices[n-1];        for(int i = n-2;i>=0;i--)        {            r[i] = max1-prices[i] > r[i+1] ? max1-prices[i] : r[i+1];            max1 = max(max1,prices[i]);        }                int ans = 0;        for(int i = 0;i<n;i++)        {            if(l[i]+r[i]>ans)                ans = l[i]+r[i];        }                return ans;    }};


0 0