遍历一次:
维持当前最大乘积imax和最小乘积imin,当出现负数时,当前最大乘积和当前最小乘积交换,
imax = Math.max(imax * nums[i], nums[i]);
imin = Math.min(imin * nums[i], nums[i]);
max = Math.max(max, imax);
/**
* 动态规划
*/
public class Solution {
public int maxProduct(int[] nums){
if(nums.length == 0)
return 0;
int max = Integer.MIN_VALUE;
int imax = 1, imin = 1;
for(int i = 0; i < nums.length; i ++){
if(nums[i] < 0){
int temp = imax;
imax = imin;
imin = temp;
}
imax = Math.max(imax * nums[i], nums[i]);
imin = Math.min(imin * nums[i], nums[i]);
max = Math.max(max, imax);
}
return max;
}
}