解题思路:
方法一:暴力
class Solution {
public int maxProduct(int[] nums) {
int max = Integer.MIN_VALUE;
int s = 1;
for (int i = 0; i < nums.length; i++) {
s = 1;
for (int j = i ; j < nums.length; j++) {
s *= nums[j];
max = Math.max(max, s);
}
}
return max;
}
}
方法二:动态规划
class Solution {
public int maxProduct(int[] nums) {
int max = Integer.MIN_VALUE, imax = 1, imin = 1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] < 0) {
int tmp = imax;
imax = imin;
imin = tmp;
}
imax = Math.max(imax * nums[i], nums[i]);
imin = Math.min(imin * nums[i], nums[i]);
max = Math.max(max, imax);
}
return max;
}
}