给定一系列时间和卖价找到最佳买卖时间使利润最大化

Given an array of time and selling price find the best buying and selling time to maximize the profit

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

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

算法有很详细的解释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);
}