查找a [i]和a [j]之间的最大可能差,其中0 <i <a.length,i <j <a.length

时间:2019-09-20 11:54:51

标签: java arrays loops

If you know the future prices of a stock, what's the best time to buy and sell?中发布了一个类似的问题,但并非完全相同。

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

我写了一个函数:

  1. 假设可以在第2天进行maxPossibleBenefit的制作

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])。

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

1 个答案:

答案 0 :(得分: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;
}