0152. Maximum Product Subarray

https://leetcode.com/problems/maximum-product-subarray

Description

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

It is guaranteed that the answer will fit in a 32-bit integer.

A subarray is a contiguous subsequence of the array.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 2 * 104

  • -10 <= nums[i] <= 10

  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

ac

// sooooo ugly and tedious, must not be the best way to solve it.
class Solution {
    public int maxProduct(int[] nums) {
        if (nums.length == 0) return 0;
        return helper(nums, 0, nums.length-1);
    }

    private int helper(int[] nums, int s, int e) {
        int len = e-s+1;
        // corner cases
        if (len == 1) return nums[s];

        // 0, zeros=[2,5,7]
        // negative, negs = [3,7,9,11]
        List<Integer> zeroIdx = new ArrayList<Integer>();
        List<Integer> negaIdx = new ArrayList<Integer>();
        for (int i = s; i <= e; i++) {
            if (nums[i] < 0) negaIdx.add(i);
            if (nums[i] == 0) zeroIdx.add(i);
        }

        int max = Integer.MIN_VALUE;

        // if has 0s
        if (zeroIdx.size() != 0) {
            if (zeroIdx.get(0) != s) max = Math.max(max, helper(nums, s, zeroIdx.get(0)-1));
            for (int i = 0; i < zeroIdx.size() - 1; i++) {
                max = Math.max(max, helper(nums, zeroIdx.get(i)+1, zeroIdx.get(i+1)-1));
            }
            if (zeroIdx.get(zeroIdx.size() - 1) != e) max = Math.max(max, helper(nums, zeroIdx.get(zeroIdx.size()-1)+1, e));
            return Math.max(max,0);
        }

        // don't have 0, but has negatives
        if (negaIdx.size() != 0) {
            if (negaIdx.size() % 2 == 0) return multiply(nums, s, e);
            max = Math.max(multiply(nums, s, negaIdx.get(negaIdx.size()-1)-1), multiply(nums, negaIdx.get(0)+1, e));
            return max;
        }

        // no 0 and negative
        return multiply(nums, s, e);
    }

    private int multiply(int[] nums, int s, int e) {
        int mul = 1;
        for (int i = s; i <= e; i++) {
            mul *= nums[i];
        }
        return mul;
    }
}

ac2: DP

idea: for each nums[i], you can multiply or discard previous result. So maintain two variables max, min in every step. Min * negative -> max, vice versa.

https://leetcode.com/problems/maximum-product-subarray/discuss/48330/Simple-Java-code

 class Solution {
    public int maxProduct(int[] nums) {
        // edge case
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];

        int max = nums[0], min = nums[0];
        int res = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int tmp1 = max * nums[i];
            int tmp2 = min * nums[i];
            max = Math.max(tmp1, Math.max(tmp2, nums[i])); // Pick max among tmp1, tmp2, nums[i], order doesn't matter.
            min = Math.min(tmp1, Math.min(tmp2, nums[i]));

            res = Math.max(res, max);
        }

        return res;
    }
}

ac3: little bit math

https://leetcode.com/problems/maximum-product-subarray/discuss/183483/JavaC%2B%2BPython-it-can-be-more-simple First, if there's no zero in the array, then the subarray with maximum product must start with the first element or end with the last element. And therefore, the maximum product must be some prefix product or suffix product. What if there are zeroes in the array? Well, we can split the array into several smaller ones. That's to say, when the prefix product is 0, we start over and compute prefix profuct from the current element instead

int maxProduct(vector<int> A) {
        int n = A.size(), res = A[0], l = 0, r = 0;
        for (int i = 0; i < n; i++) {
            l =  (l ? l : 1) * A[i];
            r =  (r ? r : 1) * A[n - 1 - i];
            res = max(res, max(l, r));
        }
        return res;
    }

Last updated