> For the complete documentation index, see [llms.txt](https://imhuay.gitbook.io/studies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/niu-ke-0083-zhong-deng-lian-xu-zi-shu-zu-de-zui-da-cheng-ji.md).

# 连续子数组的最大乘积

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-29%2023%3A59%3A13\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E4%B8%AD%E7%AD%89\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#中等) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#动态规划)

> [连续子数组的最大乘积\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/abbec6a3779940aab2cc564b22d36859)

**问题简述**

```
输入一个长度为n的整型数组nums，数组中的一个或连续多个整数组成一个子数组。求所有子数组的乘积的最大值。
```

**思路：动态规划**

* 由于乘法特性，负数乘以一个最大/小值会变最小/大值；
* 可以定义 `dp_mx, dp_mi` 分别保存以 `nums[i]` 结尾的最大乘积和最小乘积；
* 使用 `ret` 记录历史最大结果；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def maxProduct(self , nums: List[int]) -> int:
        
        ret = dp_mx = dp_mi = nums[0]
        for x in nums[1:]:
            tmp_mx, tmp_mi = dp_mx, dp_mi
            dp_mx = max(x, tmp_mx * x, tmp_mi * x)
            dp_mi = min(x, tmp_mx * x, tmp_mi * x)
            ret = max(ret, dp_mx)
            
        return ret
```

</details>
