最大单卖利润算法的最优解

C.A*_*C.A 3 java algorithm nested-loops

输入数组是:

A[0] = 23171 
A[1] = 21015 
A[2] = 21123
A[3] = 21366 
A[4] = 21013 
A[5] = 21367
Run Code Online (Sandbox Code Playgroud)

使命是找到最大的利润.例如A [3] - A [2] = 243,我的代码是:

class Solution {
    int profit = 0;
    public int solution(int[] A) {
         for (int i = 0;i < A.length; i++){
            for (int j = i + 1; j < A.length; j++){
                if(A[j] - A[i] > profit)
                    profit = A[j] - A[i];
            }
         }
         return profit;
   }
}
Run Code Online (Sandbox Code Playgroud)

结果假设是365,但它会在更大的输入上爆炸.该代码的时间复杂度为O(N 2),但可能与O(N)有关.我无法真正看到如何避免在这里筑巢......任何正确方向的指针都会受到赞赏.

Ram*_*oza 14

您只需从数组中获取最大值和最小值并将它们减去两者,因此在O(N)迭代中,获取最小值和最大值.

class Solution {

    public int solution(int[] A) {

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        for (int i = 0;i < A.length; i++){
            if(A[i] > max) max = A[i];
            if(A[i] < min) min = A[i];
        }

        return max - min;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*old 10

我认为大多数人都错了.这篇文章中的问题是最大的单一销售利润问题,这是一个典型的面试问题.

最佳解决方案:

    public int dynamicProgrammingSingleSellProfit(int[] arr) {
        if(arr.length == 0) {
            return 0;
        }
        int profit = 0;
        int cheapest = arr[0];

        for (int i = 0; i < arr.length; i++) {

            cheapest = Math.min(cheapest, arr[i]);
            profit = Math.max(profit, arr[i] - cheapest);

        }
        return profit;
    }
Run Code Online (Sandbox Code Playgroud)

它有O(n)时间和O(1)空间的复杂性.

如果你检查op正在寻找的原始问题profit,因为我们无法及时旅行()不能只比较数组中的最小值和最大值.

  • 亚当,这是一个面试测试问题是正确的.你立即发现了这一点.有什么地方我可以读到这个吗?什么意思? (2认同)