Maximum Product Subarray

Posted flagyuri

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Maximum Product Subarray相关的知识,希望对你有一定的参考价值。

Description

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

The product of the largest subsequence of the product, less than 2147483647

Example

Example 1:

Input:[2,3,-2,4]
Output:6

Example 2:

Input:[-1,2,4,1]
Output:8
思路:动态规划
public class Solution {
    /**
     * @param nums: An array of integers
     * @return: An integer
     */
    public int maxProduct(int[] nums) {
        int[] max = new int[nums.length];
        int[] min = new int[nums.length];
        
        min[0] = max[0] = nums[0];
        int result = nums[0];
        for (int i = 1; i < nums.length; i++) {
            min[i] = max[i] = nums[i];
            if (nums[i] > 0) {
                max[i] = Math.max(max[i], max[i - 1] * nums[i]);
                min[i] = Math.min(min[i], min[i - 1] * nums[i]);
            } else if (nums[i] < 0) {
                max[i] = Math.max(max[i], min[i - 1] * nums[i]);
                min[i] = Math.min(min[i], max[i - 1] * nums[i]);
            }
            
            result = Math.max(result, max[i]);
        }
        
        return result;
    }
}

  O(1)空间复杂度

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: an integer
     */
    public int maxProduct(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int minPre = nums[0], maxPre = nums[0];
        int max = nums[0], min = nums[0];
        int res = nums[0];
        for (int i = 1; i < nums.length; i ++) {
            max = Math.max(nums[i], Math.max(maxPre * nums[i], minPre * nums[i]));
            min = Math.min(nums[i], Math.min(maxPre * nums[i], minPre * nums[i]));
            res = Math.max(res, max);
            maxPre = max;
            minPre = min;
        }
        return res;
    }
}

  

以上是关于Maximum Product Subarray的主要内容,如果未能解决你的问题,请参考以下文章

152. Maximum Product Subarray

Maximum Product Subarray

152. Maximum Product Subarray

LeetCode -- Maximum Product Subarray

152. Maximum Product Subarray

Maximum Product Subarray Leetcode