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

时间:2013-11-13 16:25:11

标签: java algorithm nested-loops

输入数组是:

A[0] = 23171 
A[1] = 21015 
A[2] = 21123
A[3] = 21366 
A[4] = 21013 
A[5] = 21367

使命是找到最大的利润。例如[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;
   }
}

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

2 个答案:

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

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

它有O(n)时间和O(1)空间复杂度。

如果您检查原始问题,操作系统正在寻找profit,因为我们无法及时旅行(尚未)您不能仅仅比较最小值和最大值数组。