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

[LC] 152. Maximum Product Subarray

时间:2019-12-17 13:19:28      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:not   inpu   tput   turn   for   ret   ||   integer   ati   

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int max = nums[0];
        int min = nums[0];
        int res = nums[0];
        int preMax = max;
        for (int i = 1; i < nums.length; i++) {
            // include the current for comparison
            max = Math.max(nums[i], Math.max(preMax * nums[i], min * nums[i]));
            min = Math.min(nums[i], Math.min(min * nums[i], preMax * nums[i]));
            res = Math.max(max, res);
            preMax = max;
        }
        return res;
    }
}

[LC] 152. Maximum Product Subarray

标签:not   inpu   tput   turn   for   ret   ||   integer   ati   

原文地址:https://www.cnblogs.com/xuanlu/p/12053862.html

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