【问题标题】:Given an array of time and selling price find the best buying and selling time to maximize the profit给定一系列时间和售价,找到最佳买卖时间以最大化利润
【发布时间】:2015-07-21 13:08:05
【问题描述】:

鉴于 [ (02:00, 7.5), (03:30, 7.9), (04:00, 8.0), (05:30, 6.8), (10:00, 9.01)] 次和售价,我们需要找到买卖的最佳时机,以使利润最大化。 // 时间是递增的 // 示例输出:05:30 买入,10:00 卖出,获利 2.21

我已经编写了找到最大利润的逻辑,但我还需要找到最佳买卖时间,所以我有点卡在那里

double profit(double prices[])
  {
     double maxprofit=0;

    for(int i=0;i<price.length;i++)
    {
    double min= values[i];
    for(int j=i+1;j<price.length;j++)
    {
      if(price[j]<price[min])
      min=values[min];

    }
    profit=values[i]-min;
    if(maxprofit<profit)
    maxprofit=profit;
else
continue;
}

【问题讨论】:

  • 你卡在哪里了?
  • 你试过什么?这不是代码编写服务,而是针对特定代码相关问题的。
  • 对不起,我会更新我的代码...谢谢您的帮助
  • 谢谢丹尼尔,这很有帮助:)
  • 可能是 [SellingPoint][1] 的副本 检查我的代码并在那里回答。 [1]:stackoverflow.com/questions/7086464/maximum-single-sell-profit

标签: java arrays maximum-profit-problem


【解决方案1】:

没有必要使用嵌套循环,有一个线性时间算法可以解决这个问题。

算法here有很详细的解释。

以下是修复代码的方法:

public double maxProfit(double[] prices) {

    if (prices.length <= 1) return 0;

    double minPrice = prices[0];
    double maxSoFar = Integer.MIN_VALUE;
    double profitSoFar = Integer.MIN_VALUE;

    for (int i = 1; i < prices.length; i++){
        profitSoFar = prices[i] - minPrice;
        minPrice = Math.min(minPrice, prices[i]);
        maxSoFar = Math.max(profitSoFar, maxSoFar);

    }

    return Math.max(maxSoFar, 0);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 2019-12-22
    • 2012-03-19
    • 1970-01-01
    • 2019-06-06
    • 2011-10-28
    相关资源
    最近更新 更多