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.
解法一:比较直观的解法,首先统计数组中0的出现位置,根据0的位置把数组分割成几个部分,然后每个部分送进辅助函数,计算最大值。辅助函数是通过maintain一个最大positive的值,一个最小negative的值,一个最大negative的值,最后选择出来的。
时间复杂度O(n), 空间复杂度O(n),当数组全为0是为O(n).
public int maxProduct(int[] nums) {
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
ArrayList<Integer> list = new ArrayList<>();
int result = 0, index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) list.add(i);
}
if (list.size() == 0) {
return findmax(nums, 0, nums.length - 1);
}else {
for (int i = 0; i < list.size(); i++) {
if (index == list.get(i)) {
index++;
} else {
result = Math.max(result, findmax(nums, index, list.get(i) - 1));
index = list.get(i) + 1;
}
if (i == list.size() - 1) {
return result = Math.max(result, findmax(nums, index, nums.length - 1));
}
}
return result;
}
}
public int findmax(int[] nums, int begin, int end) {
if (begin == end) return nums[begin];
int result = 1;
int maxpos = Integer.MIN_VALUE, maxneg = Integer.MAX_VALUE, minneg = Integer.MIN_VALUE;
while (begin <= end) {
result *= nums[begin];
if (result > 0) {
if (result > maxpos) maxpos = result;
} else {
if (result > minneg) minneg = result;
if (result < maxneg) maxneg = result;
}
begin++;
}
return Math.max(maxpos, maxneg / minneg);
}
方法二:更好理解,每次都maintain一个当前最大,当前最小,和最大值,每次当前最大从(当前最大当前,当前最小当前,当前)中选择一个最大值,当前最小从(当前最大当前,当前最小当前,当前)中选择一个最小值,最大值从(当前最大,最大值)中选择一个最大值。最后返回最大值即可。其中更新当前最大/最小的时候加上当前的选择是为了解决数组中出现0的问题。
note: 这里maxherepre和minherepre不可以省略,因为如果省略了,那么maxhere计算完以后会影响计算minhere!!!
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
int maxherepre = nums[0];
int minherepre = nums[0];
int maxsofar = nums[0];
int maxhere, minhere;
for (int i = 1; i < nums.length; i++) {
maxhere = Math.max(Math.max(maxherepre * nums[i], minherepre * nums[i]), nums[i]);
minhere = Math.min(Math.min(maxherepre * nums[i], minherepre * nums[i]), nums[i]);
maxsofar = Math.max(maxhere, maxsofar);
maxherepre = maxhere;
minherepre = minhere;
}
return maxsofar;
}