java - 卖出股票的最大利润

标签 java algorithm

您的算法已经非常擅长预测市场,以至于您现在知道 Wood Orange Toothpicks Inc. (WOT) future 几天的股价将是多少。

每天,您可以购买一股 WOT,出售您拥有的任意数量的 WOT,或者根本不进行任何交易。通过最佳交易策略,您可以获得的最大利润是多少?

例如,如果您知道接下来两天的价格是价格=[1,2],您应该在第一天买入一股,然后在第二天卖出,获利 1。如果它们是 [2,1] , 没有利润,所以那些日子你不买卖股票。

样本输入

3

3

5 3 2

3

1 2 100

4

1 3 1 2

样本输出

0

197

3

我的代码是:

static int stockmax(int[] prices) {
  int temp[][]=new int[prices.length][prices.length];
    int max;
    int sum=0;
    for(int i=0;i<prices.length;i++)
    {
        max=0;
        for(int j=0;j<prices.length;j++)
        {
            if(j<=i)
            {
                temp[i][j]=0;
            }
            else{
                temp[i][j]=prices[j]-prices[i];
            }
            if(temp[i][j]>max)
                max=temp[i][j];
        }
        sum+=max;
    }
    return sum;
}

我得到了这个问题的错误答案。谁能说为什么这段代码是错误的?

最佳答案

显然,对于我们可以购买的任何价格,我们都希望以最高价格出售。幸运的是,我们得到了最高的价格。因此,向后迭代,我们知道在我们“回到过去”旅行中访问的任何时间点看到的最高 future 价格。

Python代码:

def stockmax(prices):
  n = len(prices)
  highest = prices[n - 1]
  m = [0] * n

  # Travel back in time,
  # deciding whether to buy or not
  for i in xrange(n - 2, -1, -1):

    # The most profit buying stock at this point
    # is what we may have made the next day
    # (which is stored in m[i + 1])
    # and what we could make if we bought today
    m[i] = m[i + 1] + max(
      # buy
      highest - prices[i],
      # don't buy
      0
    )

    # Update the highest "future price"
    highest = max(highest, prices[i])

  return m[0]

关于java - 卖出股票的最大利润,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52152885/

相关文章:

java - JBoss 4.2.3 - 如何查找 jar 文件的路径

c++ - 用于查找元素第一次出现的二分搜索的不变量

c - 在二叉搜索树中删除

java - Gradle 的 PMD 插件 : what are acceptable arguments?

java - 如何在不使用 JInternalFrame 的情况下在 jDesktopPane 上调用 jFrame

java - 有什么方法可以对依赖于旧版(非工作)JRE 版本的应用程序进行沙箱处理吗?

java - 编译android studio失败

python-3.x - 超出递归时间,当我尝试使用大量数据进行测试时

Python系列算法

php - 计算组合指数