Solution
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example
For example, given the array[2,3,-2,4]
, the contiguous subarray[2,3]
has the largest product =6
.
Solution
因为数组里面有正有负,所以需要同时几率dpMax和dpMin,这样遇到负数的时候,和前面的min相乘将会得到当前的max
public class Solution {
/*
* @param nums: An array of integers
* @return: An integer
*/
public int maxProduct(int[] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return 0;
}
int[] min = new int[nums.length + 1];
min[0] = 1;
int[] max = new int[nums.length + 1];
max[0] = 1;
int ret = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
max[i + 1] = Math.max(nums[i], nums[i] * max[i]);
min[i + 1] = Math.min(nums[i], nums[i] * min[i]);
} else {
max[i + 1] = Math.max(nums[i], nums[i] * min[i]);
min[i + 1] = Math.min(nums[i], nums[i] * max[i]);
}
ret = Math.max(ret, max[i + 1]);
}
return ret;
}
}