###### Middle-题目112：152. Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

dpmax[i]=max(nums[i],dpmax[i1]nums[i],dpmin[i1]nums[i])$dpmax[i]=max(nums[i],dpmax[i-1]*nums[i],dpmin[i-1]*nums[i])$
dpmin[i]=min(nums[i],dpmax[i1]nums[i],dpmin[i1]nums[i])$dpmin[i]=min(nums[i],dpmax[i-1]*nums[i],dpmin[i-1]*nums[i])$

public class Solution {
public int maxProduct(int[] nums) {
int length = nums.length;
if(length==0)
return 0;
int[] dpmax = new int[length];
int[] dpmin = new int[length];
dpmax[0] = nums[0];
dpmin[0] = nums[0];
int max = dpmax[0];
for(int i = 1;i<length;i++) {
dpmax[i] = max(nums[i],dpmax[i-1]*nums[i],dpmin[i-1]*nums[i]);
dpmin[i] = min(nums[i],dpmax[i-1]*nums[i],dpmin[i-1]*nums[i]);
if(dpmax[i]>max)
max=dpmax[i];
}
return max;
}
private int max(int a,int b,int c) {
return a>b?(a>c?a:c):(b>c?b:c);
}
private int min(int a,int b,int c) {
return a<b?(a<c?a:c):(b<c?b:c);
}
}

5ms,beats 10.47%,众数5ms,36.73%
cmershen 的碎碎念：
（1） 本题如果用一个dp数组，即dp[i][j]维护从i~j的最大乘积，也能实现但会超时。
（2） 对nums很长的情况下，可能会涉及到BigInteger高精度计算，题中没有超过int范围，故test case不够严密。
（3） 这是第一次遇到同时维护多个dp数组的题，也是拓宽了思路。

#### leetcode 152: Maximum Product Subarray

2014-12-30 09:18:02

#### LeetCode 53/152 Maximum Subarray/Maximum Product Subarray---DP **

2015-04-09 16:57:42

#### LeetCode Maximum Product Subarray 解题报告

2014-10-06 12:09:35

#### LeetCode - 152. Maximum Product Subarray - 思路详解 - C++

2017-01-16 19:26:41

#### Maximum Product Subarray -- LeetCode

2014-09-25 01:39:13

#### [LeetCode] Maximum Product Subarray的4种解法

2014-09-26 12:11:40

#### LeetCode:152. Maximum Product Subarray Java 子数组最大乘积

2016-09-05 13:52:56

#### [C++]LeetCode: 96 Maximum Product Subarray(动态规划)

2015-01-15 10:42:23

#### 【LeetCode-面试算法经典-Java实现】【152-Maximum Product Subarray（子数组的最大乘积）】

2015-08-24 07:07:12

#### 152. Maximum Product Subarray**

2017-01-15 16:56:09

## 不良信息举报

Middle-题目112：152. Maximum Product Subarray