- 题目:给定一个数组,求最大的乘积和(原题链接)
- 难度:Medium
- 思路:动态规划的题其实是有套路的,这种求极值的题绝大多数可以用动态规划解决,定义变量currMax, currMin, max, 根据nums[i]是否大于等于0,分为两种情况更新currMax和currMin,每次更新完currMax,都需要更新max
- 代码:
public class Solution {
public int maxProduct(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int len = nums.length;
int currMax = nums[0];
int currMin = nums[0];
int max = nums[0];
for(int i=1; i < len; i++){
if(nums[i] >= 0){
currMax = Math.max(currMax*nums[i],nums[i]);
currMin = Math.min(currMin*nums[i],nums[i]);
}else{
int temp = currMax;
currMax = Math.max(currMin*nums[i],nums[i]);
currMin = Math.min(temp*nums[i],nums[i]);
}
max = Math.max(max, currMax);
}
return max;
}
}