> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0152-maximum-product-subarray.md).

# 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

```java
// 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>

```java
 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

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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jaywin.gitbook.io/leetcode/solutions/0152-maximum-product-subarray.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
