Best Time to Buy and Sell Stock III

来源:互联网 发布:python 贝叶斯分类器 编辑:程序博客网 时间:2024/06/06 07:23

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 max(vector<int>& prices, int s, int e)    {        if (s >= e) return 0;        int ret = 0;        int min = prices[s];        for (int i = s + 1; i <= e; i++)        {            if (prices[i] < min)                min = prices[i];            else if (prices[i] - min > ret)            {                ret = prices[i] - min;            }        }        return ret;    }    int maxProfit(vector<int> &prices)    {        if (prices.size() <= 1) return 0;        int ret = 0;        for (int i = 0; i < prices.size(); i++)        {            int cur = max(prices, 0, i) + max(prices, i, prices.size() - 1);            ret = ret > cur ? ret : cur;        }        return ret;    }};
第二次通过,利用动态规划时间复杂度O(n),逆序遍历与顺序不同的是,逆序是记录最大值并于当前值比较,顺序是记录最小值,并与当前值比较


class Solution {public:    int maxProfit(vector<int> &prices)    {       if (prices.size() <= 1) return 0;              int N = prices.size();       vector<int> dp;       int min = prices[0];              dp.push_back(0);       for (int i = 1; i < N; i++)       {           min = min > prices[i] ? prices[i] : min;           int tmp = prices[i] - min;           dp.push_back(tmp > dp[i-1] ? tmp : dp[i-1]);       }       int max = prices[N - 1];       int maxProf = 0;       int ret = 0;       for (int i = N-2; i >= 0; i--)       {           max = max > prices[i] ? max : prices[i];           maxProf = maxProf > max - prices[i] ? maxProf : max - prices[i];           ret = ret > maxProf + dp[i] ? ret : maxProf + dp[i];       }       return ret;    }};



0 0