# 152. Maximum Product Subarray

[Given an integer array `nums`, find the contiguous subarray within an array (containing at least one number) which has the largest product.](https://leetcode.com/problems/maximum-product-subarray/)

{% hint style="info" %}
dynamic programming, use a int to keep track of minimal product of subarrays

```java
dp[i+1] = Math.max(nums[i+1], dp[i]*nums[i+1], preMin*nums[i+1]);
```

{% endhint %}

```java
class Solution {
    public int maxProduct(int[] nums) {
        // let dp[i] be the largest product of subarray end at index of i
        // let preMin be the smallest product of subarray end at index of i
        // dp[i+1] = Math.max(nums[i+1], dp[i]*nums[i+1], preMin*nums[i+1]);
        
        // use int to record min prodction
        int preMin = nums[0];
        // use nums[] to record max production
        
        int res = nums[0];
        for (int i=1; i<nums.length; i++){
            int min = Math.min(preMin*nums[i], nums[i-1]*nums[i]);        
            int max = Math.max(preMin*nums[i], nums[i-1]*nums[i]);
            preMin = Math.min(nums[i], min);
            
            nums[i] = Math.max(nums[i], max);                        
            res = nums[i]>res ? nums[i] : res;
            
        }
        return res;
    }
}
```


---

# Agent Instructions: 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://ucan.gitbook.io/notes/dynamic-programming/152.-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.
