Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
思路:注意本题,最大数可能是最小数乘以当前值得到(当最小数为负,当前数也是负的时候),也可能是最大数乘以当前值得到
代码如下(已通过leetcode)
public class Solution {
public int maxProduct(int[] nums) {
if(nums==null||nums.length==0) return 0;
int n=nums.length;
int[] dp=new int[n];
dp[0]=nums[0];
int max=nums[0];
int min=nums[0];
for(int i=1;i<n;i++) {
int a=nums[i]*max;
int b=nums[i]*min;
max=Math.max(Math.max(a, b), nums[i]);
min=Math.min(Math.min(a, b), nums[i]);
dp[i]=Math.max(max, dp[i-1]);
}
return dp[n-1];
}
}