1.题目
给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
2.解法
public int FindMaxProduct(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 tmp = max;
max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]);
min = Math.min(Math.min(min * nums[i], tmp * nums[i]), nums[i]);
// 求最大值一直在算,有可能越算越小
if (max > result){
resutl = max;
}
}
return result;
}
时间复杂度O(n), 空间复杂度O(1)