LeetCode 152. 乘积最大子序列
一、题目详情
给你一个整数数组 nums
,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 连续子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是连续子数组。
二、动态规划法
本题可以用动态规划法解决。在遍历数组时记录当前最大乘积并不断更新。
但由于是乘积所以需要考虑正负问题,此时维护两个变量tempMax
和tempMin
,当遍历到的数据为负数时,会导致最大乘积变成最小乘积,最小乘积变成最打乘积。此时将tempMax
和tempMin
进行对调,再进行下一步运算。
class Solution {
public int maxProduct(int[] nums) {
//动态规划
int max = Integer.MIN_VALUE,tempMax = 1,tempMin = 1;
for(int i = 0;i < nums.length;i++){
if(nums[i] < 0){
tempMax = tempMax + tempMin;
tempMin = tempMax - tempMin;
tempMax = tempMax - tempMin;
}
tempMax = Math.max(nums[i],tempMax * nums[i]);
tempMin = Math.min(nums[i],tempMin * nums[i]);
max = Math.max(max,tempMax);
}
return max;
}
}