【问题标题】:best time to buy and sell stock dynamic programming买卖股票动态规划的最佳时机
【发布时间】:2018-03-20 08:12:44
【问题描述】:

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

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

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

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

dp[i][j] = max(dp[i][j], max(prices[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)

【问题讨论】:

  • 你是指先买后卖的最大利润吗?因为否则它只是最小值和最大值。
  • @Carlos:是的,先买后卖。

标签: python algorithm dynamic-programming


【解决方案1】:

一个提示是对价格进行预处理,并找出以指数 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;

}

【讨论】:

  • Prefix-sum + Kadane 算法?
  • 它不会完全是前缀总和,因为利润不会总是前缀总和。
  • @PriyanshGoel:我用另一种方式解决了这个问题,即从左边跟踪到 i 的最大利润,从右边跟踪到 i 的最大利润。将 0(n) 中的左右利润加起来。您现在可以提出您的解决方案吗?
  • @nomanpouigt :我正在做同样的事情,但没有维护正确的数组。您只能在左侧数组中执行此操作。
  • @PriyanshGoel:可以为此发布一些伪代码吗?
【解决方案2】:
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

【讨论】:

  • 运行时,内存优化的pythonic解决方案!
猜你喜欢
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2020-10-04
  • 2021-10-06
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
相关资源
最近更新 更多