购买和出售股票动态节目的最佳时机

时间:2017-10-09 07:34:49

标签: python algorithm dynamic-programming

试图解决this:假设您有一个数组,其中第i个元素是第i天给定股票的价格。

设计算法以找到最大利润。您最多可以完成两笔交易。

解决方案: 我正在做的是分而治之的方法。

dp [i] [j] ith jth 日之间的最大利润。计算方法如下:

dp [i] [j] = max(dp [i] [j],max(price [i] - prices [j],dp [k] [j],dp [i] [k +1])),其中k小于i且大于j。

现在我们只需要在下面找出两笔交易的最大利润:

m = max(m,max(dp [i] [j],dp [k] [j] + dp [i] [k + 1]))

请给我提示来解决此问题,因为此处提供的现有解决方案已超时。

class Solution(object):
    def profit(self, prices, dp):
        m = 0
        for w in range(1, len(prices)):
            for i in range(1, len(prices)):
                for j in range(i-w, i):
                    if i-w < 0:
                        continue
                    for k in range(j, i):
                        dp[i][j] = max(dp[i][j], max(prices[i] - prices[j], dp[k][j], dp[i][k+1]))
                        m = max(m, max(dp[i][j], dp[k][j] + dp[i][k+1]))
        return m

    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        dp = [[0 for i in range(len(prices)+1)] for i in range(len(prices)+1)]
        return self.profit(prices, dp)

2 个答案:

答案 0 :(得分:2)

一个提示是预先处理价格,并找出以指数i结束的价格出售可以赚取的最大利润。 然后,您可以从预处理向量的末尾开始,找出问题的解决方案。这将解决使用1-D DP的问题,并且不会超时。

  int maxProfit(vector<int>& prices) {

    int mprof = 0;
    if (prices.size()>1){
        int maxprof = 0;
        vector<int> mp; // max profit before each element
        mp.push_back(0);
        int st = *prices.begin();
        for(int i = 1 ; i<=prices.size();i++){  //compute mp vector
            if (mprof < prices[i]-st){mprof = prices[i]-st;}
            if (prices[i]<st){st = prices[i];}
            mp.push_back(mprof);
        }
        mprof = 0;
        int ed = *(prices.end()-1);
        for (int i = prices.size()-2; i>=0; i--){
            if (mprof < ed - prices[i] + mp[i]) { mprof = ed - prices[i] + mp[i];}
            if (prices[i]>ed) {ed = prices[i];}
        }
    }
    return mprof;

}

答案 1 :(得分:0)

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) <= 1:
            return 0

        max_profit = 0
        buy_price = prices[0]
        for price in prices:
            if price >= buy_price:
                max_profit += price - buy_price
                buy_price = price
            else:
                buy_price = price


        return max_profit