1

给定 [ (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;
}
4

1 回答 1

2

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

这里对算法有非常详细的解释。

以下是修复代码的方法:

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);
}
于 2015-05-11T06:42:30.430 回答