【问题标题】:find max possible difference between a[i] and a[j], where 0 < i < a.length and i < j < a.length找到 a[i] 和 a[j] 之间的最大可能差异,其中 0 < i < a.length 和 i < j < a.length
【发布时间】:2019-09-20 11:54:51
【问题描述】:

If you know the future prices of a stock, what's the best time to buy and sell? 也有类似的问题,但并不完全相同。

给定:一个整数数组代表一个项目的股票价格 问题:如果我们在第 X 天卖出一股,然后在第 X+n 天卖出,找到最大可能的收益。

我写了一个函数:

  1. 假设 maxPossibleBenefit 可以在第 2 天完成:

1.1 maxPossibleBenefit = a[1] - a[0]

  1. 从a[0]遍历数组到a[a.length -1]:

2.1 如果a[X+n] - a[X] > maxPossibleBenefit,则maxPossibleBenefit = a[X+n] - a[X]。

3.当X+n == a.length(我们到达数组的末尾)时,从a[1]开始重复步骤2和2.1,然后从a[2]开始,直到我们到达a.[length- 2] 比较最后 2 个元素。

public static int maxBenefit(int[] arr) {

        //first, assuming that max benefit can be received on day 2
        int maxBenefit = arr[1] - arr[0];
        // traverse the entire array and check,
        // will we get more benefit if we buy on day one
        // and sell on day 2, 3, up until the last day in the range:
        for (int i = 0; i < arr.length - 1; i++) {
            // with every run we shift purchase date by one into the future
            for (int j = i; j < arr.length - 1; j++) {
                // if we sell later than on day 2, will we get more benefit?
                if ((arr[j + 1] - arr[j]) > maxBenefit)
                    maxBenefit = arr[j + 1] - arr[j];
            }
        }
        return maxBenefit;
    }

但是对于数组 {8, 6, 5, 6, 7, 9, 10, 7, 9, 4},函数返回 2,而它应该是 5 (a[6] - a[2])。

您能帮我找出算法中的缺陷吗?

【问题讨论】:

  • 你试过用调试器运行它吗?
  • 其实没有,我还没学会怎么用。是的,真丢脸。

标签: java arrays loops


【解决方案1】:

你没有正确使用i和j,也没有计算它们之间的差异。

public static int maxBenefit(int[] arr) {

    //first, assuming that max benefit can be received on day 2
    int maxBenefit = arr[1] - arr[0];
    // traverse the entire array and check,
    // will we get more benefit if we buy on day one
    // and sell on day 2, 3, up until the last day in the range:
    for (int i = 0; i < arr.length - 1; ++i) {
        // with every run we shift purchase date by one into the future
        for (int j = i + 1; j < arr.length; ++j) {
            // if we sell later than on day 2, will we get more benefit?
            int benefit = arr[j] - arr[i];
            if ( benefit > maxBenefit)
                maxBenefit = benefit;
        }
    }
    return maxBenefit;
}

【讨论】:

  • 谢谢,现在我知道缺陷在哪里了。非常感谢,这解决了问题!
猜你喜欢
  • 2013-08-19
  • 1970-01-01
  • 2017-09-10
  • 2021-04-09
  • 1970-01-01
  • 2013-05-06
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多