原题描述:
找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
例如, 给定序列 [2,3,-2,4]
,
其中乘积最大的子序列为 [2,3]
其乘积为 6
。
解答:
1. 暴力搜索---O(n^2)
没有AC:超时
class Solution {
public int maxProduct(int[] nums) {
int n = nums.length;
int max = nums[0];
int ans;
for(int i = 0;i < n;++i){
ans = nums[i];
if(ans > max)
max = ans;
if(i != n - 1){
for(int j = i + 1;j < n;++j){
ans *= nums[j];
if(ans > max)
max = ans;
}
}
}
return max;
}
}
2. 动态规划思想,max & min
每有一个新的数字加入,最大值要么是当前最大值*新数,要么是当前最小值(负数)*新数(负数),要么是当前值。
class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = nums[0], min = nums[0], result = nums[0];
for (int i = 1; i < nums.length; i++) {
int temp = max;
max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]);
min = Math.min(Math.min(temp * nums[i], min * nums[i]), nums[i]);
if (max > result) {
result = max;
}
}
return result;
}
}