码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 152. Maximum Product Subarray

时间:2019-03-28 23:23:06      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:actually   sam   []   class   product   ret   java   prefix   tco   

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;
    }
}

leetcode 152. Maximum Product Subarray

标签:actually   sam   []   class   product   ret   java   prefix   tco   

原文地址:https://www.cnblogs.com/exhausttolive/p/10618328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!