152 Maximum Product Subarray
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
使用动态规划,每遍历到一个点时,记录当前位置的最大值和最小值,到新的位置,新的位置的值,以及新的位置的值与前一个节点的最大值和最小值的乘积,这三个数中的最大值和最小值是新位置的最大值和最小值。记录其中的最大值。
class Solution {
public int maxProduct(int[] nums) {
int max=nums[0];
int big=max, small=max;
for(int i=1;i<nums.length;++i){
int cur=nums[i];
int next1=cur*big;
int next2=cur*small;
big=max(cur, next1, next2);
small=min(cur, next1, next2);
if(big>max) max=big;
}
return max;
}
private int max(int i1, int i2, int i3){
if(i1>i2){
if(i1>i3) return i1;
} else {
if(i2>i3) return i2;
}
return i3;
}
private int min(int i1, int i2, int i3){
if(i1<i2){
if(i1<i3) return i1;
} else {
if(i2<i3) return i2;
}
return i3;
}
}