leetcode 152. Maximum Product Subarray

Use prefix product(sum? actually much the same).

class Solution {
    public int maxProduct(int[] nums) {
        int maxNeg = 1, minPos = 1;
        int product = 1;
        int ret = Integer.MIN_VALUE;
        for (int val: nums) {
            product *= val;
            if (product == 0) { 
                ret = Math.max(ret, val);
                product = maxNeg = minPos =  1;
            }
            else if (product > 0) {
                ret = Math.max(ret, product / minPos);
                minPos = Math.min(minPos, product);
            }
            else {
                ret = Math.max(ret, product / maxNeg);
                maxNeg = maxNeg > 0? product: Math.max(maxNeg, product);
            }
        }
        return ret == Integer.MIN_VALUE? 0: ret;
    }
}
posted on 2019-03-28 22:44  王 帅  阅读(76)  评论(0编辑  收藏  举报