[leetCode] Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

參考了 @ych_ding 的方法,比我原來的簡潔太多。

public class Solution {
    public int maxProduct(int[] A) {
        if (A.length == 0) return 0;
        if (A.length == 1) return A[0];

        int min = A[0];
        int max = A[0];
        int res = max;

        for (int i = 1; i < A.length; i++) {
            int tmp1 = min * A[i];
            int tmp2 = max * A[i];
            min = Math.min(A[i], Math.min(tmp1, tmp2));
            max = Math.max(A[i], Math.max(tmp1, tmp2));
            res = Math.max(max, res);
        }

        return res;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章