题目
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
解题思路
思想:动态规划
- 遍历整个数组,计算当前最大值和最小值
- 当出现负数时,最大值需要和最小值交换(因为负数会使最大值变小,最小值变大)
- 每次遍历一个元素,记录当前最大值,遍历完数组后,返回记录的值即可。
代码实现
class Solution {
public int maxProduct(int[] nums) {
int ans = Integer.MIN_VALUE;
int currentMax = 1;
int currentMin = 1;
for (int i = 0; i < nums.length; i++) {
//出现负数,最大值和最小值交换
if( nums[i] < 0){
int temp = currentMax;
currentMax = currentMin;
currentMin = temp;
}
//记录当前最大值和最小值
currentMax = Math.max(currentMax*nums[i], nums[i]);
currentMin = Math.min(currentMin*nums[i], nums[i]);
ans = Math.max(currentMax, ans);
}
return ans;
}
}
复杂度分析
-
时间复杂度:程序一次循环遍历了 n u m s nums nums,故时间复杂度为 O ( n ) O(n) O(n)。
-
空间复杂度:只使用常数个临时变量作为辅助空间,与 n n n 无关,故空间复杂度为 O ( 1 ) O(1) O(1)。