---
# System prepended metadata

title: 0152. Maximum Product Subarray
tags: [Leetcode, Dynamic Programming, Medium]

---

# 0152. Maximum Product Subarray
###### tags: `Leetcode` `Medium` `Dynamic Programming`
Link: https://leetcode.com/problems/maximum-product-subarray/
## 思路
和[0053. Maximum Subarray](https://hackmd.io/qpgZUbERQVOXcw9DSBI1Mw)差不多
但因为过程中有可能涉及变号(最小变最大 最大变最小)
所以要保留现在的最小值和最大值
## Code
```java=
class Solution {
    public int maxProduct(int[] nums) {
        int max = nums[0];
        int prevMax = nums[0], prevMin = nums[0];
        for(int i=1; i<nums.length; i++){
            int num = nums[i];
            int currMax = Math.max(Math.max(prevMax*num, prevMin*num), num);
            int currMin = Math.min(Math.min(prevMin*num, prevMax*num), num);
            prevMax = currMax;
            prevMin = currMin;
            max = Math.max(currMax, max);
        }
        return max;
    }
}
```